From david.nearing@ns.sympatico.ca Mon Oct 1 02:17:02 2001 From: david.nearing@ns.sympatico.ca (David Nearing) Date: Sun, 30 Sep 2001 18:17:02 -0700 Subject: [Tutor] gym 10 Message-ID: <20010930211843.AAA28705@mail-ns00s0.ns.sympatico.ca@[142.177.210.22]> ****VIRUS ALERT***** This message originally contained a virus. The virus content has been removed. --Aliant Telecom. From sales@dazoneusa.com Mon Oct 1 04:44:29 2001 From: sales@dazoneusa.com (sales@dazoneusa.com) Date: Mon, 1 Oct 2001 12:44:29 +0900 (´ëÇѹα¹ Ç¥ÁؽÃ) Subject: [Tutor] DaZoneUSA proudly presents new release of Webebuilder 5.1 Message-ID: <3BB4745E.14915@kang.dazone.co.kr> --Boundary-=_xySfjCJEVwhXthkmkcNbdHTzTpGz Content-Type: Text/HTML Content-Transfer-Encoding: base64 PGh0bWw+DQoNCjxoZWFkPg0KPHRpdGxlPkRhWm9uZVVTQSBwcm91ZGx5IHByZXNlbnRzIG5ldyBy ZWxlYXNlIG9mIFdlYmVidWlsZGVyIDUuMSE8L3RpdGxlPg0KPGxpbmsgcmVsPSJzdHlsZXNoZWV0 IiBocmVmPSJodHRwOi8vd3d3LmRhem9uZXVzYS5jb20vc3R5bGUuY3NzIiB0eXBlPSJ0ZXh0L2Nz cyI+DQo8L2hlYWQ+DQoNCjxib2R5IGJnY29sb3I9IiNGRkZGRkYiIHRleHQ9ImJsYWNrIiBsaW5r PSJibHVlIiB2bGluaz0icHVycGxlIiBhbGluaz0icmVkIiBsZWZ0bWFyZ2luPSIwIiBtYXJnaW53 aWR0aD0iMCIgdG9wbWFyZ2luPSIwIiBtYXJnaW5oZWlnaHQ9IjAiPg0KPHRhYmxlIGJvcmRlcj0i MCIgY2VsbHBhZGRpbmc9IjAiIGNlbGxzcGFjaW5nPSIwIiB3aWR0aD0iNzU5IiBoZWlnaHQ9IjEw MCUiPg0KICA8dHIgYWxpZ249ImxlZnQiIHZhbGlnbj0idG9wIj4NCiAgICA8dGQgYmdjb2xvcj0i I0ZGRkZGRiIgd2lkdGg9Ijc0Ij48aW1nIHNyYz0iaHR0cDovL3d3dy5kYXpvbmV1c2EuY29tL2lt Zy9tZW51X2ltZy9kb3QuZ2lmIiB3aWR0aD0iMTAiIGhlaWdodD0iMTAiPjwvdGQ+DQogICAgPHRk IHdpZHRoPSI0NCIgYmdjb2xvcj0iI0ZGRkZGRiI+Jm5ic3A7PC90ZD4NCiAgICA8dGQgd2lkdGg9 IjY0MSI+IA0KICAgICAgPHRhYmxlIGJvcmRlcj0iMCIgY2VsbHNwYWNpbmc9IjAiIGNlbGxwYWRk aW5nPSIwIiB3aWR0aD0iNTc5IiBiZ2NvbG9yPSIjRkZGRkZGIj4NCiAgICAgICAgPHRyIGFsaWdu PSJsZWZ0IiB2YWxpZ249InRvcCI+IA0KICAgICAgICAgIDx0ZCB3aWR0aD0iNTU0IiBoZWlnaHQ9 Ijk0MSI+IA0KICAgICAgICAgICAgPGRpdiBhbGlnbj0iY2VudGVyIj4NCiAgICAgICAgICAgICAg PHA+Jm5ic3A7PC9wPg0KICAgICAgICAgICAgICA8cD48Yj48Zm9udCBzaXplPSI1IiBmYWNlPSJB cmlhbCwgSGVsdmV0aWNhLCBzYW5zLXNlcmlmIiBjb2xvcj0iIzAwMDA5OSI+PGZvbnQgY29sb3I9 IiMzMzAwOTkiPkRhWm9uZVVTQSANCiAgICAgICAgICAgICAgICBwcm91ZGx5IHByZXNlbnRzIG5l dyByZWxlYXNlIG9mIFdlYmVidWlsZGVyIDUuMTwvZm9udD48L2ZvbnQ+PC9iPjxicj4NCiAgICAg ICAgICAgICAgPC9wPg0KICAgICAgICAgICAgPC9kaXY+DQogICAgICAgICAgICA8dGFibGUgd2lk dGg9IjEwMCUiIGJvcmRlcj0iMCIgY2VsbHNwYWNpbmc9IjEiIGNlbGxwYWRkaW5nPSIxIj4NCiAg ICAgICAgICAgICAgPHRyPiANCiAgICAgICAgICAgICAgICA8dGQgY29sc3Bhbj0iMiIgaGVpZ2h0 PSIzNiI+IA0KICAgICAgICAgICAgICAgICAgPGRpdiBhbGlnbj0iY2VudGVyIj4gDQogICAgICAg ICAgICAgICAgICAgIDxwPjxmb250IHNpemU9IjIiPkNyZWF0ZSBwcm9mZXNzaW9uYWxseSBsb29r aW5nIGRhdGFiYXNlLWRyaXZlbiANCiAgICAgICAgICAgICAgICAgICAgICB3ZWJzaXRlIHdpdGhv dXQgd2ViLXByb2dyYW1taW5nIGtub3dsZWRnZSE8L2ZvbnQ+PC9wPg0KICAgICAgICAgICAgICAg ICAgPC9kaXY+DQogICAgICAgICAgICAgICAgPC90ZD4NCiAgICAgICAgICAgICAgPC90cj4NCiAg ICAgICAgICAgICAgPHRyPiANCiAgICAgICAgICAgICAgICA8dGQgd2lkdGg9IjMlIiByb3dzcGFu PSIyIj4mbmJzcDs8L3RkPg0KICAgICAgICAgICAgICAgIDx0ZCB3aWR0aD0iOTclIj4gDQogICAg ICAgICAgICAgICAgICA8cD48aW1nIHNyYz0iaHR0cDovL3d3dy5kYXpvbmV1c2EuY29tL2ltZy9z dWJfaW1nL3Byb2R1Y3RfZWJ1aWxkZXJfdGl0bGUuZ2lmIiB3aWR0aD0iNTAwIiBoZWlnaHQ9IjMy MSI+PGJyPg0KICAgICAgICAgICAgICAgICAgPC9wPg0KICAgICAgICAgICAgICAgIDwvdGQ+DQog ICAgICAgICAgICAgIDwvdHI+DQogICAgICAgICAgICAgIDx0cj4gDQogICAgICAgICAgICAgICAg PHRkIHdpZHRoPSI5NyUiIGhlaWdodD0iMTAyIj4gDQogICAgICAgICAgICAgICAgICA8cD48Yj5X ZWJlQnVpbGRlcjwvYj4gaXMgYSBjb21wbGV0ZSBmcmFtZXdvcmsgZm9yIGludGVncmF0aW5nIA0K ICAgICAgICAgICAgICAgICAgICBXZWIgYW5kIERhdGFiYXNlIHRlY2hub2xvZ2llcy4gV2ViZUJ1 aWxkZXIgaW5jbHVkZXMgZGV2ZWxvcG1lbnQgDQogICAgICAgICAgICAgICAgICAgIHRvb2xzIHBs dXMgYWRkaXRpb25hbCBwYWNrYWdlZCBzb2Z0d2FyZSBtb2R1bGVzIHdpdGggdmFyaW91cyANCiAg ICAgICAgICAgICAgICAgICAga2V5IGZ1bmN0aW9ucy4gQWxsIGZlYXR1cmVzIGFyZSBkZXNpZ25l ZCB0byBtYWtlIFdlYmVCdWlsZGVyIA0KICAgICAgICAgICAgICAgICAgICB0aGUgbW9zdCBwcmFj dGljYWwgc3lzdGVtIGZvciBidWlsZGluZyBXZWItZGF0YWJhc2UgYXBwbGljYXRpb25zLiANCiAg ICAgICAgICAgICAgICAgICAgV2ViIHBob3RvIGRhdGFiYXNlLCBjdXN0b21lciBkYXRhYmFzZSwg cHJvZHVjdCBkYXRhYmFzZSwgc2NyYXBib29rLCANCiAgICAgICAgICAgICAgICAgICAgZWxlY3Ry b25pYyBkb2N1bWVudCBtYW5hZ2VtZW50IGFuZCBtYW55IG90aGVyIHN5c3RlbXMgY2FuIA0KICAg ICAgICAgICAgICAgICAgICBiZSBidWlsdCBzbyBlYXNpbHkgdXNpbmcgV2ViZUJ1aWxkZXIuIElu IGFkZGl0aW9uIHRvIHRoZSBhYm92ZSANCiAgICAgICAgICAgICAgICAgICAgaW5jcmVkaWJsZSBj YXBhYmlsaXRpZXMsIFdlYmVCdWlsZGVyIGhhcyB0aGUgc3BlY2lhbCBmdW5jdGlvbnMgDQogICAg ICAgICAgICAgICAgICAgIGZvciBidWlsZGluZyB0aGUgb2ZmaWNlIGF1dG9tYXRpb24gZW52aXJv bm1lbnRzLCB3aGljaCBhcmUgDQogICAgICAgICAgICAgICAgICAgIEdyb3Vwd2FyZSwgRURNUyhF bGVjdHJvbmljIGRvY3VtZW50IE1hbmFnZW1lbnQgU3lzdGVtKSBhbmQgDQogICAgICAgICAgICAg ICAgICAgIEVJUChFbnRlcnByaXNlIEluZm9ybWF0aW9uIHBvcnRhbCkgc3VwcG9ydGluZyBmdW5j dGlvbnMgc3VjaCANCiAgICAgICAgICAgICAgICAgICAgYXMgbXkgcG9ydGFsLCBzaW5nbGUgbG9n b24sIHBlcnNvbmFsaXphdGlvbiwgdW5pZmllZCBhY2Nlc3MsIA0KICAgICAgICAgICAgICAgICAg ICBhdXRvbWF0aWMgbm90aWZpY2F0aW9uIGFuZCBldGMuIE1vc3Qgb2YgYW55IGtpbmQgb2YgV2Vi IHNpdGVzIA0KICAgICAgICAgICAgICAgICAgICBydW5uaW5nIG9uIGRhdGFiYXNlIGNhbiBiZSBi dWlsdCBzbyBxdWlja2x5IHdpdGhvdXQgYW4gZWZmb3J0IA0KICAgICAgICAgICAgICAgICAgICB1 c2luZyBXZWJlQnVpbGRlci4gV2ViZUJ1aWxkZXIgaGFzIGJlZW4gZGVzaWduZWQgdG8gYmUgZWFz eSANCiAgICAgICAgICAgICAgICAgICAgdG8gdXNlIGV2ZW4gZm9yIHRob3NlIHdobyBoYXZlIG5v IHByZXZpb3VzIGRhdGFiYXNlIG9yIHdlYiANCiAgICAgICAgICAgICAgICAgICAgZGV2ZWxvcG1l bnQgZXhwZXJpZW5jZS4gQXMgc29vbiBhcyB0aGUgaW5zdGFsbGF0aW9uIGlzIGNvbXBsZXRlLCAN CiAgICAgICAgICAgICAgICAgICAgYW4gYWRtaW5pc3RyYXRvciwgdXNpbmcgYSBwb3B1bGFyIGJy b3dzZXIgc3VjaCBhcyBOZXRzY2FwZSANCiAgICAgICAgICAgICAgICAgICAgb3IgTVMgRXhwbG9y ZXIsIGNhbiBjb25uZWN0IGFuZCBzZWUgdGhlIGFkbWluaXN0cmF0b3IncyBtZW51IA0KICAgICAg ICAgICAgICAgICAgICBzY3JlZW4gb2YgV2ViZUJ1aWxkZXIuIFRoZSBhZG1pbmlzdHJhdG9yIGlz IG5vdyByZWFkeSB0byBidWlsZCANCiAgICAgICAgICAgICAgICAgICAgaGlzIG93biBkYXRhYmFz ZXMgYW5kIHJlbGF0ZWQgSFRNTCBmb3JtcyBlZmZvcnRsZXNzbHksIGVmZmVjdGl2ZWx5IA0KICAg ICAgICAgICAgICAgICAgICBhbmQgcXVpY2tseS4gPC9wPg0KICAgICAgICAgICAgICAgICAgPHAg YWxpZ249InJpZ2h0Ij48YSBocmVmPSJodHRwOi8vd3d3LmRhem9uZXVzYS5jb20vcGFydG5lcl9m cjIuaHRtIj48Yj4mZ3Q7Jmd0O01vcmUgDQogICAgICAgICAgICAgICAgICAgIEluZm9ybWF0aW9u PC9iPjwvYT48L3A+DQogICAgICAgICAgICAgICAgPC90ZD4NCiAgICAgICAgICAgICAgPC90cj4N CiAgICAgICAgICAgICAgPHRyPiANCiAgICAgICAgICAgICAgICA8dGQgd2lkdGg9IjMlIiBoZWln aHQ9IjEwMyI+Jm5ic3A7PC90ZD4NCiAgICAgICAgICAgICAgICA8dGQgd2lkdGg9Ijk3JSIgaGVp Z2h0PSIxMDMiPiANCiAgICAgICAgICAgICAgICAgIDxwIGFsaWduPSJjZW50ZXIiPjxiPlRyeSBX ZWJlYnVpbGRlciByaWdodCBub3chPC9iPjwvcD4NCiAgICAgICAgICAgICAgICAgIDxwIGFsaWdu PSJjZW50ZXIiPjxhIGhyZWY9Imh0dHA6Ly93d3cuZGF6b25ldXNhLmNvbS9kb3dubG9hZF9mci5o dG0iPjxpbWcgc3JjPSJodHRwOi8vd3d3LmRhem9uZXVzYS5jb20vaW1nL2Rsb2FkLWJuLmdpZiIg d2lkdGg9IjMwIiBoZWlnaHQ9IjMwIiBhbGlnbj0idG9wIiBib3JkZXI9IjAiDQo+PGI+IA0KICAg ICAgICAgICAgICAgICAgICA8Zm9udCBzaXplPSI0Ij5Eb3dubG9hZCBOb3c8L2ZvbnQ+PC9iPiA8 L2E+PC9wPg0KICAgICAgICAgICAgICAgICAgPHAgYWxpZ249ImNlbnRlciI+IEZyZWUgZG93bmxv YWQgMzUuN01CIDwvcD4NCiAgICAgICAgICAgICAgICA8L3RkPg0KICAgICAgICAgICAgICA8L3Ry Pg0KICAgICAgICAgICAgICA8dHI+IA0KICAgICAgICAgICAgICAgIDx0ZCB3aWR0aD0iMyUiPiZu YnNwOzwvdGQ+DQogICAgICAgICAgICAgICAgPHRkIHdpZHRoPSI5NyUiPiANCiAgICAgICAgICAg ICAgICAgIDxwPjxiPkdlbmVyYWwgRmVhdHVyZXM8L2I+PC9wPg0KICAgICAgICAgICAgICAgICAg PHRhYmxlIHdpZHRoPSI1MTYiIGJvcmRlcj0iMCIgY2VsbHNwYWNpbmc9IjAiIGNlbGxwYWRkaW5n PSIwIiBhbGlnbj0iY2VudGVyIj4NCiAgICAgICAgICAgICAgICAgICAgPHRyPiANCiAgICAgICAg ICAgICAgICAgICAgICA8dGQ+PGltZyBzcmM9Imh0dHA6Ly93d3cuZGF6b25ldXNhLmNvbS9pbWcv c3ViX2ltZy9saW5lX3RvcDEuZ2lmIiB3aWR0aD0iNTE2IiBoZWlnaHQ9IjgiPjwvdGQ+DQogICAg ICAgICAgICAgICAgICAgIDwvdHI+DQogICAgICAgICAgICAgICAgICAgIDx0cj4gDQogICAgICAg ICAgICAgICAgICAgICAgPHRkIGJnY29sb3I9IiNFNkU2RTYiIGhlaWdodD0iOTkiPiANCiAgICAg ICAgICAgICAgICAgICAgICAgIDxkaXYgYWxpZ249ImxlZnQiPiANCiAgICAgICAgICAgICAgICAg ICAgICAgICAgPHVsPg0KICAgICAgICAgICAgICAgICAgICAgICAgICAgIDxsaT5FYXN5IGluc3Rh bGxhdGlvbiBhbmQgbWFuYWdlbWVudCBvbiB0aGUgd2ViPGJyPg0KICAgICAgICAgICAgICAgICAg ICAgICAgICAgIDwvbGk+DQogICAgICAgICAgICAgICAgICAgICAgICAgICAgPGxpPlN0cmFpZ2h0 Zm9yd2FyZCBkYXRhYmFzZSBjcmVhdGlvbiBhbmQgTWFuYWdlbWVudCANCiAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgIDxicj4NCiAgICAgICAgICAgICAgICAgICAgICAgICAgICA8L2xpPg0K ICAgICAgICAgICAgICAgICAgICAgICAgICAgIDxsaT5XZWIgYmFzZWQgZW1haWwgc2VydmVyIDxi cj4NCiAgICAgICAgICAgICAgICAgICAgICAgICAgICA8L2xpPg0KICAgICAgICAgICAgICAgICAg ICAgICAgICAgIDxsaT5FSVAgKEVudGVycHJpc2UgSW5mb3JtYXRpb24gUG9ydGFsKSBhbmQgZ3Jv dXB3YXJlIA0KICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgZnVuY3Rpb248YnI+DQogICAg ICAgICAgICAgICAgICAgICAgICAgICAgPC9saT4NCiAgICAgICAgICAgICAgICAgICAgICAgICAg ICA8bGk+RGF0YWJhc2UgYW5kIEhUTUwgZmlsZXMgaW1wb3J0LCBleHBvcnQgYW5kIER1cGxpY2F0 aW9uIA0KICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgPGJyPg0KICAgICAgICAgICAgICAg ICAgICAgICAgICAgIDwvbGk+DQogICAgICAgICAgICAgICAgICAgICAgICAgICAgPGxpPkEgd2lk ZSByYW5nZSBvZiBjb21wYXRpYmxlIHBsYXRmb3JtcyBhbmQgZGF0YWJhc2UgDQogICAgICAgICAg ICAgICAgICAgICAgICAgICAgPC9saT4NCiAgICAgICAgICAgICAgICAgICAgICAgICAgPC91bD4N CiAgICAgICAgICAgICAgICAgICAgICAgIDwvZGl2Pg0KICAgICAgICAgICAgICAgICAgICAgIDwv dGQ+DQogICAgICAgICAgICAgICAgICAgIDwvdHI+DQogICAgICAgICAgICAgICAgICAgIDx0cj4g DQogICAgICAgICAgICAgICAgICAgICAgPHRkPjxpbWcgc3JjPSJodHRwOi8vd3d3LmRhem9uZXVz YS5jb20vaW1nL3N1Yl9pbWcvbGluZV90b3AyLmdpZiIgd2lkdGg9IjUxNiIgaGVpZ2h0PSI4Ij48 L3RkPg0KICAgICAgICAgICAgICAgICAgICA8L3RyPg0KICAgICAgICAgICAgICAgICAgPC90YWJs ZT4NCiAgICAgICAgICAgICAgICA8L3RkPg0KICAgICAgICAgICAgICA8L3RyPg0KICAgICAgICAg ICAgPC90YWJsZT4NCiAgICAgICAgICAgIDxicj4NCiAgICAgICAgICA8L3RkPg0KICAgICAgICAg IDx0ZCB3aWR0aD0iMjUiIGhlaWdodD0iOTQxIj4gDQogICAgICAgICAgICA8cD48YnI+DQogICAg ICAgICAgICA8L3A+DQogICAgICAgICAgICA8cD4mbmJzcDs8L3A+DQogICAgICAgICAgPC90ZD4N CiAgICAgICAgPC90cj4NCiAgICAgICAgPHRyIGFsaWduPSJsZWZ0IiB2YWxpZ249InRvcCI+IA0K ICAgICAgICAgIDx0ZCB3aWR0aD0iNTU0Ij4NCiAgICAgICAgICAgIDxkaXYgYWxpZ249ImNlbnRl ciI+PGJyPg0KICAgICAgICAgICAgICA8Zm9udCBjb2xvcj0iIzY2NjY2NiI+Q29weXJpZ2h0KGMp IDE5OTYtMjAwMTxhIGhyZWY9Imh0dHA6Ly93d3cuZGF6b25ldXNhLmNvbSI+IA0KICAgICAgICAg ICAgICBEYVpvbmVVU0E8L2E+IEFsbCByaWdodHMgcmVzZXJ2ZWQuIDwvZm9udD48L2Rpdj4NCiAg ICAgICAgICA8L3RkPg0KICAgICAgICAgIDx0ZCB3aWR0aD0iMjUiPiZuYnNwOzwvdGQ+DQogICAg ICAgIDwvdHI+DQogICAgICA8L3RhYmxlPg0KICAgIDwvdGQ+DQogIDwvdHI+DQogIDx0ciBhbGln bj0ibGVmdCIgdmFsaWduPSJ0b3AiPiANCiAgICA8dGQgd2lkdGg9Ijc0IiBiZ2NvbG9yPSIjRTdG NEZGIj48L3RkPg0KICAgIDx0ZCB3aWR0aD0iNDQiIGJnY29sb3I9IiNFN0Y0RkYiPjwvdGQ+DQog ICAgPHRkIHdpZHRoPSI2NDEiPjwvdGQ+DQogIDwvdHI+DQo8L3RhYmxlPg0KPC9ib2R5Pg0KDQo8 L2h0bWw+DQo= --Boundary-=_xySfjCJEVwhXthkmkcNbdHTzTpGz-- From kromag@nsacom.net Mon Oct 1 07:18:04 2001 From: kromag@nsacom.net (kromag@nsacom.net) Date: Sun, 30 Sep 2001 23:18:04 -0700 (PDT) Subject: [Tutor] bsddb - mystery wrapped in enigma Message-ID: <200110010618.f916I4Y16888@pop.nsacom.net> I have been scouring the earth for a good tutorial on the bsddb module. Is there anything (in print or otherwise) lurking about that might help? I am trying to extract information from an existing berkeley db file (sleepycat). Thanks! d From alevin@alevin.com Mon Oct 1 07:05:09 2001 From: alevin@alevin.com (Adina Levin) Date: Mon, 1 Oct 2001 01:05:09 -0500 Subject: [Tutor] newbie question: help with polymorphism and/or programming style Message-ID: <08ec01c14a3f$07150e20$b756fea9@ValuedCustomer> This is a multi-part message in MIME format. ------=_NextPart_000_08E9_01C14A15.1DB8BF20 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hello, Python tutors. I am teaching myself python programming, and have created a toy = storefront program, and would greatly appreciate some words of wisdom on = programming style. The code below is for payment. If the customer wants to pay with cash, the program should return = change. If the customer wants to pay using a credit card, the program should = validate the customer's ability to pay, and return an approval. The programming style qeustions are as follows: a) Is it desirable to replace the "if" statement in paymenthandler with subclasses, PayCash(Payment) and PayCredit(Payment). If so, doesn't = that just push the "if" statement upstream, where you PayCash() if the = customer says she wants to pay cash? I am clearly missing something!! :-( b) Is it bad style to return different kinds of information, depending = on whether the customer pays with cash or credit? If so, how should this be handled cleanly? c) Any other programming style problems? This is a toy, so no reason to comment on lack of full detail in the simulation. class Payment: def __init__(self): self.payobject=3DCustomer().getpaymentinput() def payhandler(self,sum): self.sum=3Dsum if self.payobject.paytype =3D=3D "cash": result=3Dself.payobject.cashamount-self.sum print result elif self.payobject.paytype =3D=3D "credit": self.crednum=3Dself.payobject.crednum result=3DCreditcheck().creditapprove(self) return result ------=_NextPart_000_08E9_01C14A15.1DB8BF20 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hello, Python tutors.

I am = teaching myself=20 python programming, and have created a toy storefront
program, and = would=20 greatly appreciate some words of wisdom on programming=20 style.
 
The code below is for=20 payment.
If the customer wants to pay with = cash, the=20 program should return change. If
the customer wants to pay using a = credit=20 card, the program should validate
the customer's ability to pay, and = return=20 an approval.

The programming style qeustions are as = follows:

a) Is=20 it desirable to replace the "if" statement in paymenthandler = with
subclasses,=20 PayCash(Payment) and PayCredit(Payment).  If so, doesn't = that
just push=20 the "if" statement upstream, where you PayCash() if the customer
says = she=20 wants to pay cash?  I am clearly missing something!! :-(

b) = Is it=20 bad style to return different kinds of information, depending = on
whether the=20 customer pays with cash or credit? If so, how should this be
handled=20 cleanly?

c) Any other programming style problems?

This is = a toy,=20 so no reason to comment on lack of full detail in=20 the
simulation.

class Payment:
    def=20 __init__(self):
       =20 self.payobject=3DCustomer().getpaymentinput()

    = def=20 payhandler(self,sum):
       =20 self.sum=3Dsum
        if=20 self.payobject.paytype =3D=3D=20 "cash":
          &n= bsp;=20 result=3Dself.payobject.cashamount-self.sum
    &n= bsp;      =20 print result

        elif=20 self.payobject.paytype =3D=3D=20 "credit":
          =  =20 self.crednum=3Dself.payobject.crednum
     &n= bsp;     =20 result=3DCreditcheck().creditapprove(self)

    = ;   =20 return result


------=_NextPart_000_08E9_01C14A15.1DB8BF20-- From rnd@onego.ru Mon Oct 1 08:32:36 2001 From: rnd@onego.ru (Roman Suzi) Date: Mon, 1 Oct 2001 11:32:36 +0400 (MSD) Subject: [Tutor] newbie question: help with polymorphism and/or programming style In-Reply-To: <08ec01c14a3f$07150e20$b756fea9@ValuedCustomer> Message-ID: On Mon, 1 Oct 2001, Adina Levin wrote: > Hello, Python tutors. > > The programming style qeustions are as follows: > > a) Is it desirable to replace the "if" statement in paymenthandler with > subclasses, PayCash(Payment) and PayCredit(Payment). If so, doesn't that > just push the "if" statement upstream, where you PayCash() if the customer > says she wants to pay cash? I am clearly missing something!! :-( It is easier to make choices nearer to the place of decision, because it helps build better abstraction. > b) Is it bad style to return different kinds of information, depending on > whether the customer pays with cash or credit? If so, how should this be > handled cleanly? Yes, it is not very good. Because after having 20+ classes you will be lost with interfaces and exceptions from rules. Better give similar things similar interface. Your class combines Payment and ValidatePaymentMeans and this is not good. Probably better solution is to have CashPayment(Payment) CreditCardPayment(Payment) ValidateCreditCard(ValidatePaymentMeans) ValidateCash(ValidatePaymentMeans) (could be hooked to the appropriate device ;-) or be dummy) as separate classes. > c) Any other programming style problems? > > This is a toy, so no reason to comment on lack of full detail in the > simulation. > > class Payment: > def __init__(self): > self.payobject=Customer().getpaymentinput() > > def payhandler(self,sum): > self.sum=sum > if self.payobject.paytype == "cash": > result=self.payobject.cashamount-self.sum > print result > > elif self.payobject.paytype == "credit": > self.crednum=self.payobject.crednum > result=Creditcheck().creditapprove(self) > > return result > > > Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd@onego.ru - From runsun@bilbo.bio.purdue.edu Mon Oct 1 08:38:53 2001 From: runsun@bilbo.bio.purdue.edu (Run-Sun Pan) Date: Mon, 1 Oct 2001 02:38:53 -0500 (EST) Subject: [Tutor] Class: property? function list? Message-ID: <200110010738.CAA26676@bilbo.bio.purdue.edu> Dear all, [1] --- "property" in class ??? Is there any "property" in class? For example, mc = myclass() mc.hitcount = 100 #<===== user input x = mc.hitcount print x In the above example there's no validation whatsoever. As long as the 100 is passed to .hitcount, no matter it's a string or even other object type, it will be past to x. I want to have this .hitcount value validated before it is returned to other variable x. In some other object-oriented languages you can define "properties" for a class for this purpose. Is there such device in python ? [2] --- list all variables and functions of myclass Is there a way to get a list of all the "names" of all the variable and function names of my own class ? Thx in advance. pan From ak@silmarill.org Mon Oct 1 08:45:11 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Mon, 01 Oct 2001 03:45:11 -0400 Subject: [Tutor] Class: property? function list? In-Reply-To: <200110010738.CAA26676@bilbo.bio.purdue.edu> References: <200110010738.CAA26676@bilbo.bio.purdue.edu> Message-ID: <20011001034511.A7981@sill.silmarill.org> On Mon, Oct 01, 2001 at 02:38:53AM -0500, Run-Sun Pan wrote: > Dear all, > > [1] --- "property" in class ??? > > Is there any "property" in class? For example, > > mc = myclass() > mc.hitcount = 100 #<===== user input > x = mc.hitcount > print x > > In the above example there's no validation > whatsoever. As long as the 100 is passed to > .hitcount, no matter it's a string or even > other object type, it will be past to x. > > I want to have this .hitcount value validated > before it is returned to other variable x. In > some other object-oriented languages you can > define "properties" for a class for this purpose. > Is there such device in python ? > > [2] --- list all variables and functions of > myclass > > Is there a way to get a list of all the "names" > of all the variable and function names of my > own class ? > > Thx in advance. > > pan You could do this: class MyClass: def set_count(self, count): if type(count) != type(1): print "error" else: self.hit_count = count mc = MyClass() mc.set_count("test") # prints error mc.set_count(5) # valid - Andrei -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From shalehperry@home.com Mon Oct 1 08:49:52 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Mon, 01 Oct 2001 00:49:52 -0700 (PDT) Subject: [Tutor] Class: property? function list? In-Reply-To: <200110010738.CAA26676@bilbo.bio.purdue.edu> Message-ID: On 01-Oct-2001 Run-Sun Pan wrote: > Dear all, > > [1] --- "property" in class ??? > > Is there any "property" in class? For example, > > mc = myclass() > mc.hitcount = 100 #<===== user input > x = mc.hitcount > print x > > In the above example there's no validation > whatsoever. As long as the 100 is passed to > .hitcount, no matter it's a string or even > other object type, it will be past to x. > > I want to have this .hitcount value validated > before it is returned to other variable x. In > some other object-oriented languages you can > define "properties" for a class for this purpose. > Is there such device in python ? > The best I have seen done is to define __setattr__ and __getattr__. def __setattr__(self, name, vale): if name == 'hitcount': if value < 0 or value > 1000: value = 0 self.dict['hitcount'] = value def __getattr__(self, name): return self.dict[name] and in __init__() you just initialize dict and any variables you maintain. From lsloan@umich.edu Mon Oct 1 15:20:18 2001 From: lsloan@umich.edu (Lance E Sloan) Date: Mon, 01 Oct 2001 10:20:18 -0400 Subject: [Tutor] Python program, seg. faults and dies Message-ID: <200110011420.KAA10538@birds.us.itd.umich.edu> A colleague of mine was written a Python program that causes a segmentation fault and dies under Solaris 2.6. I ran it and got it to produce a coredump file, but I'm not sure how to get the Python program and core file loaded into the debugger, GDB. I've done so with C programs, but GDB says it doesn't recognize the Python program as an executable. If anybody has experience with this, could you drop me a line? -- Lance E Sloan Web Services, Univ. of Michigan: Full-service Web and database design, development, and hosting. Specializing in Python & Perl CGIs. http://websvcs.itd.umich.edu/ - "Putting U on the Web" From agauld@crosswinds.net Mon Oct 1 18:23:04 2001 From: agauld@crosswinds.net (agauld@crosswinds.net) Date: Mon, 1 Oct 2001 18:23:04 +0100 Subject: [Tutor] My web site Message-ID: <17301118709219@mailth4.freenet.co.uk> Hi folks, I'm back from leave and it looks like crosswinds have managed to lose my entire web site! - including my tutor in all language versions. This is, as they say, outwith my control but I am now looking for another (free) web provider. I'll drop a message to this group and the various page owners once I get a new site set up. To make things worse the older xoom.com (aka nbci) site seems dead too! Thankfully I keep a reference copy on my PC! Sincere apologies to anyone looking for the site. Alan g From wilson@visi.com Mon Oct 1 18:52:05 2001 From: wilson@visi.com (Timothy Wilson) Date: Mon, 1 Oct 2001 12:52:05 -0500 (CDT) Subject: [Tutor] My web site In-Reply-To: <17301118709219@mailth4.freenet.co.uk> Message-ID: On Mon, 1 Oct 2001 agauld@crosswinds.net wrote: > I'm back from leave and it looks like crosswinds have managed to > lose my entire web site! - including my tutor in all language > versions. I assume you've got a backup? If not, I've got the whole thing mirrored as of Sept. 1 or so. -Tim -- Tim Wilson | Visit Sibley online: | Check out: Henry Sibley HS | http://www.isd197.org | http://www.zope.com W. St. Paul, MN | | http://slashdot.org wilson@visi.com | | http://linux.com From ak@silmarill.org Mon Oct 1 19:17:15 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Mon, 01 Oct 2001 14:17:15 -0400 Subject: [Tutor] My web site In-Reply-To: <17301118709219@mailth4.freenet.co.uk> References: <17301118709219@mailth4.freenet.co.uk> Message-ID: <20011001141715.A10303@sill.silmarill.org> On Mon, Oct 01, 2001 at 06:23:04PM +0100, agauld@crosswinds.net wrote: > Hi folks, > > I'm back from leave and it looks like crosswinds have managed to > lose my entire web site! - including my tutor in all language > versions. > > This is, as they say, outwith my control but I am now looking for > another (free) web provider. I'll drop a message to this group and > the various page owners once I get a new site set up. > > To make things worse the older xoom.com (aka nbci) site seems > dead too! Thankfully I keep a reference copy on my PC! > > Sincere apologies to anyone looking for the site. > > Alan g Why don't you buy webspace from one of the really cheap hosts like pair.net (very professional, ~$5/mo?) or digitalspace.net (less professional, but $36/year, plus python). I used both and they're not bad at all. With free hosts.. well, you get what you pay for i guess :-). [snip] - Andrei -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From gbcs1978@hotmail.com Mon Oct 1 19:52:57 2001 From: gbcs1978@hotmail.com (Glauco Silva) Date: Mon, 1 Oct 2001 15:52:57 -0300 Subject: [Tutor] Help - Doubt of Listbox Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_002D_01C14A91.241EDBC0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi men , I'm new member of this list and i have a doubt of programing = in Python : - I would like to know how i can mount two listbox and put Directories = in the first one and files of the directories in the second listbox . Thank you=20 Glauco ------=_NextPart_000_002D_01C14A91.241EDBC0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi men , I'm new member of this list = and i have a=20 doubt of programing  in Python :
 
- I would like to know how i can = mount  two=20 listbox and put Directories in the first one and files of the = directories in the=20 second listbox .
 
Thank you
Glauco
 
------=_NextPart_000_002D_01C14A91.241EDBC0-- From Doy" This is a multi-part message in MIME format. ------=_NextPart_000_0052_01C14A89.5E4C05A0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi i want to know if there is a way to compile a python file to a .exe = file... so everybody can run it without installing python or NEEDING A = DLL... thanks! ------=_NextPart_000_0052_01C14A89.5E4C05A0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi i want to know if there is a way to = compile a=20 python file to a .exe file... so everybody can run it without installing = python=20 or NEEDING A DLL... thanks!
------=_NextPart_000_0052_01C14A89.5E4C05A0-- From rob@jam.rr.com Mon Oct 1 20:02:20 2001 From: rob@jam.rr.com (Rob Andrews) Date: Mon, 01 Oct 2001 14:02:20 -0500 Subject: [Tutor] Useless delays Message-ID: <3BB8BDBC.6020903@jam.rr.com> Useless Python has also suffered lately. The website is currently up, but I've encountered so many problems in the last few weeks (in between viruses and post-WTC complications, having to free my #2 staff member from the burden of continued employment, losing Internet service for a week, etc.) that I've been unable to perform necessary website maintenance. I'm glad Useless is still up, because I actually did lose the backup. Please forgive the month of delays. I'll get things caught up soon, even if I have to take on some assistance. I'm curious, though, what would become of Useless Python if I took off to Nepal to do some chanting and teach former nomadic herders from Tibet how to do IT work. Any thoughts out there? (Useless could probably be placed at Sourceforge if all else fails.) -Rob From riddlebox@vitalogy.org Mon Oct 1 19:37:15 2001 From: riddlebox@vitalogy.org (RIDDLE BOX) Date: Mon, 1 Oct 2001 11:37:15 -0700 Subject: [Tutor] help Message-ID: <200110011837.LAA10234@mail12.bigmailbox.com> I am having trouble trying to get a loop into my program, and I am wondering if someone could help me better understand using "while"? here is a copy of the code that I am having trouble with if someone could explain what I am doing wrong I would appreciate it thanks def second_chance(self): j = second while j = open: read = raw_input("where is the file located?") inp = open(read, "r") for line in inp.readlines(): print line ------------------------------------------------------------ This Email Is Provided Free Of Charge Thanks To http://www.vitalogy.org Sponsored by: http://www.iminteractive.net Internet Solutions, web host & more! From ak@silmarill.org Mon Oct 1 21:53:03 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Mon, 01 Oct 2001 16:53:03 -0400 Subject: [Tutor] help In-Reply-To: <200110011837.LAA10234@mail12.bigmailbox.com> References: <200110011837.LAA10234@mail12.bigmailbox.com> Message-ID: <20011001165303.A10835@sill.silmarill.org> On Mon, Oct 01, 2001 at 11:37:15AM -0700, RIDDLE BOX wrote: > I am having trouble trying to get a loop into my program, and I am wondering if someone could help me better understand using "while"? > > here is a copy of the code that I am having trouble with if someone could explain what I am doing wrong I would appreciate it thanks > > def second_chance(self): > j = second > while j = open: ^ What's that?? This isn't valid python code. I don't know what it's supposed to do , either. > read = raw_input("where is the file located?") > inp = open(read, "r") > for line in inp.readlines(): > print line > > > > ------------------------------------------------------------ > This Email Is Provided Free Of Charge Thanks To http://www.vitalogy.org > Sponsored by: http://www.iminteractive.net Internet Solutions, web host & more! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From dyoo@hkn.eecs.berkeley.edu Mon Oct 1 22:01:46 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 1 Oct 2001 14:01:46 -0700 (PDT) Subject: [Tutor] help In-Reply-To: <200110011837.LAA10234@mail12.bigmailbox.com> Message-ID: On Mon, 1 Oct 2001, RIDDLE BOX wrote: > I am having trouble trying to get a loop into my program, and I am > wondering if someone could help me better understand using "while"? > > here is a copy of the code that I am having trouble with if someone > could explain what I am doing wrong I would appreciate it thanks > > def second_chance(self): > j = second > while j = open: > read = raw_input("where is the file located?") > inp = open(read, "r") > for line in inp.readlines(): > print line The "while" loop is sorta similar to the "for" loop in that it allows us to repeat things over and over. While the "for" loop iterates over a sequence of things, "while" does something while a condition is true. For example: ### while 1: print "I am an infinite loop." ### will run in an infinite loop because "1" is considered to be a true value in Python. Here's another example: ### print "Counting down" x = 10 while x >= 0: print x x = x - 1 ### Let's take a look at your program snippet again: > def second_chance(self): > j = second > while j = open: > read = raw_input("where is the file located?") > inp = open(read, "r") > for line in inp.readlines(): > print line There's some small syntax that can be easily corrected: the body of the while loop needs to be indented. However, I have to admit that I'm a little confused about how the program plans to use the while loop. Can you explain a little more about what you want to do? Maybe then we can see if the while loop is a good thing to use for this method. Best of wishes to you. From dyoo@hkn.eecs.berkeley.edu Tue Oct 2 08:12:22 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 2 Oct 2001 00:12:22 -0700 (PDT) Subject: [Tutor] Help - Doubt of Listbox In-Reply-To: Message-ID: On Mon, 1 Oct 2001, Glauco Silva wrote: > Hi men , I'm new member of this list and i have a doubt of programing > in Python : Hello! By the way: it's not just men in here; we welcome all genders, nationalities, carbon-based and non-carbon-based lifeforms to Tutor. Welcome aboard! > - I would like to know how i can mount two listbox and put Directories > in the first one and files of the directories in the second listbox . We can create a Frame() that will house those two listboxes: ### >>> frame = Frame(root) >>> frame.pack() ### Not too exciting yet, since there's nothing in the frames yet. Let's add two listboxes to that frame: ### >>> dir_listbox = Listbox(frame) >>> files_listbox = Listbox(frame) >>> dir_listbox.pack() >>> files_listbox.pack() ### By this time, we should have two listboxes on-screen. That takes care of much of the GUI side of things. Now all we need to do is add things into those Listboxes. There are a few functions in the 'os' module that might be useful, as well as the 'glob' module. You can find out about both on the Library Documentation site of Python.org: http://python.org/doc/lib One thing that should be added: it sounds like you're writing a file browser of some kind. If so, you might want to see if someone has done this already, as it's quite a bit of work. There are collections of widgets from the Python Megeawidgets project: http://pmw.sourceforge.net Anyway, hope this helps. What other questions do you have? If you have more questions, please feel free to ask the list. From dyoo@hkn.eecs.berkeley.edu Tue Oct 2 08:05:00 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 2 Oct 2001 00:05:00 -0700 (PDT) Subject: [Tutor] help (fwd) Message-ID: Dear Riddle Box, I have to apologize in advance; I haven't had time to answer your question yet. To make sure it actually gets answered, let me forward it to the rest of Python's Tutor list. When talking to people on tutor, try to keep the messages on-list, so that others can learn and comment. (I actually have something of a presentation that's due on Thursday, so I'm somewhat out of commission for the moment.) Best of wishes to you! ---------- Forwarded message ---------- Date: Mon, 1 Oct 2001 17:54:00 -0700 From: RIDDLE BOX To: dyoo@hkn.eecs.berkeley.edu Subject: RE: Re: [Tutor] help Hello, I may have the been trying to do this wrong with that code, but I would like the program to look at a file and then when you are done looking at that file, I would like it to ask if you would like to look at another file, and keep asking that until you quit the program. this is my whole code right now. I hope I am on the right track. thanks for all your help :) class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text="quit", fg="blue", command=frame.quit) self.button.pack(side=RIGHT) self.second_chance = Button(frame, text="would you like to look at another file?", fg="red", command=self.second_chance) self.second_chance.pack(side=LEFT) def second_chance(self): read = raw_input("where is the file located?") inp = open(read, "r") for line in inp.readlines(): print line root = Tk() app = App(root) >Date: Mon, 1 Oct 2001 14:01:46 -0700 (PDT) > Danny Yoo RIDDLE BOX cc: tutor@python.org > Re: [Tutor] help >On Mon, 1 Oct 2001, RIDDLE BOX wrote: > >> I am having trouble trying to get a loop into my program, and I am >> wondering if someone could help me better understand using "while"? >> >> here is a copy of the code that I am having trouble with if someone >> could explain what I am doing wrong I would appreciate it thanks >> >> def second_chance(self): >> j = second >> while j = open: >> read = raw_input("where is the file located?") >> inp = open(read, "r") >> for line in inp.readlines(): >> print line > >The "while" loop is sorta similar to the "for" loop in that it allows us >to repeat things over and over. > > >While the "for" loop iterates over a sequence of things, "while" does >something while a condition is true. > >For example: > >### >while 1: > print "I am an infinite loop." >### > >will run in an infinite loop because "1" is considered to be a true value >in Python. > > >Here's another example: > >### >print "Counting down" >x = 10 >while x >= 0: > print x > x = x - 1 >### > > > >Let's take a look at your program snippet again: > >> def second_chance(self): >> j = second >> while j = open: >> read = raw_input("where is the file located?") >> inp = open(read, "r") >> for line in inp.readlines(): >> print line > >There's some small syntax that can be easily corrected: the body of the >while loop needs to be indented. > >However, I have to admit that I'm a little confused about how the program >plans to use the while loop. Can you explain a little more about what you >want to do? Maybe then we can see if the while loop is a good thing to >use for this method. > > >Best of wishes to you. ------------------------------------------------------------ This Email Is Provided Free Of Charge Thanks To http://www.vitalogy.org Sponsored by: http://www.iminteractive.net Internet Solutions, web host & more! From agauld@crosswinds.net Tue Oct 2 08:41:00 2001 From: agauld@crosswinds.net (agauld@crosswinds.net) Date: Tue, 2 Oct 2001 08:41:00 +0100 Subject: [Tutor] my web site Message-ID: <07480662505578@mailth4.freenet.co.uk> My web site is up again in limited form - English only. The key thing is that the zip and tgz files are both available so via themn the whole site as it was can be grabbed(again English only) Hopefully by close of play today I'll have the foreign zip files up too. This is hindered by crosswinds not providing ftp access only web uploads - OK for a few files but a pain for major work! I have also applied to a new Web space provider - hopefully with no adverts... Thanks for the messages of support. Alan G From pemrograman@telkom.net Tue Oct 2 22:07:53 2001 From: pemrograman@telkom.net (Adinda Praditya) Date: Wed, 3 Oct 2001 04:07:53 +0700 Subject: [Tutor] Client Server Programming Message-ID: <000c01c14b86$4de2e1e0$0101a8c0@workgroup> This is a multi-part message in MIME format. ------=_NextPart_000_0009_01C14BC0.F94F1C80 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable hi All,... I'm gonna build a client/server program controlled by an admin, (never = built it before). I'd like to know the basic thought of making this. = What section of manual or docs should i read? Is there any API (visual = programming) so i can make it easier? thank you, and sorry for my bad english. dida ------=_NextPart_000_0009_01C14BC0.F94F1C80 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
hi All,...
 
I'm gonna build a client/server program = controlled=20 by an admin, (never built it before). I'd like to know the basic thought = of=20 making this. What section of manual or docs should i read? Is there any = API=20 (visual programming) so i can make it easier?
 
thank you, and sorry for my bad=20 english.
 
dida
------=_NextPart_000_0009_01C14BC0.F94F1C80-- From sampatel@cs.rmit.edu.au Tue Oct 2 10:13:49 2001 From: sampatel@cs.rmit.edu.au (Samir Patel) Date: Tue, 2 Oct 2001 19:13:49 +1000 (EST) Subject: [Tutor] html programming ??? Message-ID: hi all, i am trying to write python script which takes a url and opens that page ...then i am trying to grab all the links present in that page and want to put that links in a data structure..... now my problem is that how do i use a data structure and how should i put this links into that..... following is my code : #!/usr/local/bin/python import sys import urllib import re url = sys.argv[1] try: fp = urllib.urlopen(url) except IOError: fp = ('*** ERROR: invalid URL ***') done = 0 while not done: line = fp.readline() if line != "": link = re.findall('href="(.*?)"', line) if len(link) != 0: for get_link in link: print url + " " + "->" + " " + get_link else: done=1 fp.close() hopw u guys can help me !!!! thanks samir From sheila@thinkspot.net Tue Oct 2 15:19:49 2001 From: sheila@thinkspot.net (Sheila King) Date: Tue, 02 Oct 2001 07:19:49 -0700 Subject: [Tutor] my web site In-Reply-To: <07480662505578@mailth4.freenet.co.uk> References: <07480662505578@mailth4.freenet.co.uk> Message-ID: <684864746BE@kserver.org> On Tue, 2 Oct 2001 08:41:00 +0100, agauld@crosswinds.net wrote about [Tutor] my web site: :My web site is up again in limited form - English only. :The key thing is that the zip and tgz files are both available so :via themn the whole site as it was can be grabbed(again English :only) : :Hopefully by close of play today I'll have the foreign zip files up too. : :This is hindered by crosswinds not providing ftp access only web :uploads - OK for a few files but a pain for major work! : :I have also applied to a new Web space provider - hopefully with no :adverts... : :Thanks for the messages of support. Maybe I should have suggested this sooner, but it might be useful for future reference??? I've use http://free.prohosting.com/ as a free host. They do provide FTP access and limited CGI and SSI (CGI is Perl only). I think you get .htaccess also. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From dsh8290@rit.edu Tue Oct 2 16:19:06 2001 From: dsh8290@rit.edu (dman) Date: Tue, 2 Oct 2001 11:19:06 -0400 Subject: [Tutor] my web site In-Reply-To: <07480662505578@mailth4.freenet.co.uk>; from agauld@crosswinds.net on Tue, Oct 02, 2001 at 08:41:00AM +0100 References: <07480662505578@mailth4.freenet.co.uk> Message-ID: <20011002111906.C4468@harmony.cs.rit.edu> On Tue, Oct 02, 2001 at 08:41:00AM +0100, agauld@crosswinds.net wrote: | My web site is up again in limited form - English only. | The key thing is that the zip and tgz files are both available so | via themn the whole site as it was can be grabbed(again English | only) | | Hopefully by close of play today I'll have the foreign zip files up too. | | This is hindered by crosswinds not providing ftp access only web | uploads - OK for a few files but a pain for major work! Yeah, but couldn't you use a python script to walk through the directory (locally) and issue an HTTP PUT for each file? -D From dsh8290@rit.edu Tue Oct 2 16:57:03 2001 From: dsh8290@rit.edu (dman) Date: Tue, 2 Oct 2001 11:57:03 -0400 Subject: [Tutor] Client Server Programming In-Reply-To: <000c01c14b86$4de2e1e0$0101a8c0@workgroup>; from pemrograman@telkom.net on Wed, Oct 03, 2001 at 04:07:53AM +0700 References: <000c01c14b86$4de2e1e0$0101a8c0@workgroup> Message-ID: <20011002115703.F4468@harmony.cs.rit.edu> On Wed, Oct 03, 2001 at 04:07:53AM +0700, Adinda Praditya wrote: | hi All,... | | I'm gonna build a client/server program controlled by an admin, | (never built it before). I'd like to know the basic thought of | making this. What section of manual or docs should i read? Is there | any API (visual programming) so i can make it easier? What platform do the components need to run on? How much low-level work do you want to do, versus how much work learning and setting up a middleware package? For school I have had to write some trivial distributed systems. First we had to write it using sockets and create our own protocol. This can be done and doesn't rely on any 3rd party software, but is a lot of work for little gain. Then we used RMI (yeah, the course is taught with Java), and most recently CORBA. I tried out the CORBA stuff with Python (using the orbit-python bindings on my Debian box) and it is really cool and fairly simple to create and use distributed objects. I recommend CORBA if you have the flexibility to choose a good set of bindings to a good orb. HTH, -D From alan.gauld@bt.com Tue Oct 2 17:21:40 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 2 Oct 2001 17:21:40 +0100 Subject: [Tutor] Client Server Programming Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFAA@mbtlipnt02.btlabs.bt.co.uk> > | I'm gonna build a client/server program controlled by an admin, > | (never built it before). I'd like to know the basic thought of > | making this. What section of manual or docs should i read? Is there > | any API (visual programming) so i can make it easier? Visual programming is available for doing C/S work but IMHO doesn't add much benefit beyond a GUI builder for the client. [Exception being if you use a heavyweight middleware tool with work-flow, business rules validation etc then Vitria or Versata or BEA or whatever do provide benefits - but at big bucks cost] > First we had to write it using sockets and create our own protocol. > This can be done and doesn't rely on any 3rd party software, but is a > lot of work for little gain. Hmm, sockets are usually my default option. Unless the protocol is very complex or the number of messages very rich(>50 say) I tend to opt for sockets - easy to write, easy to debug and fairly performant. 'Course security and scaleability etc are poor (or must be hand crafted)... > Then we used RMI (yeah, the course is > taught with Java), and most recently CORBA. CORBA is good for heterogenous environments. BUt theres quite an administrative headache attached if/when you need to move servers around. Also consider XML-RPC. A very easy to use solution that exposes a procedural rather than OO API in the shape of XML messages. There is a Python implementation and an O'Reilly book plus the usual Web docs. Great for multiple environments and low-medium transaction volumes.(say less than 10/second) Alan G. From kalle@gnupung.net Tue Oct 2 17:45:44 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Tue, 2 Oct 2001 18:45:44 +0200 Subject: [Tutor] Client Server Programming In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFAA@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFAA@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20011002184543.F7776@sandrew.lysator.liu.se> [alan.gauld@bt.com] > > | I'm gonna build a client/server program controlled by an admin, > > | (never built it before). I'd like to know the basic thought of > > | making this. What section of manual or docs should i read? Is there > > | any API (visual programming) so i can make it easier? [snip] > Also consider XML-RPC. A very easy to use solution that exposes > a procedural rather than OO API in the shape of XML messages. > There is a Python implementation and an O'Reilly book plus the > usual Web docs. Great for multiple environments and low-medium > transaction volumes.(say less than 10/second) +1. XML-RPC is very nice as long as performance isn't crucial. The main features in my opinion is that the protocol is easy to understand, and that the transmitted data is human-readable. Makes debugging *much* easier. Peace, Kalle -- [ Thought control, brought to you by the WIPO! ] [ http://anti-dmca.org/ http://eurorights.org/ ] From jeff@ccvcorp.com Tue Oct 2 17:50:23 2001 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue, 02 Oct 2001 09:50:23 -0700 Subject: [Tutor] html programming ??? References: Message-ID: <3BB9F04E.C7D29952@ccvcorp.com> > hi all, > i am trying to write python script which takes a url and opens that page > ...then i am trying to grab all the links present in that page and want > to put that links in a data structure..... > now my problem is that how do i use a data structure and how should i put > this links into that..... Hi Samir A few minor pointers. First, the re module is probably more powerful than what you need. It will certainly work, but you could do much the same thing with string.find(), which is much simpler. However, I'll keep the re in place in my example below, so that this change doesn't obscure the other changes I'm making. Also, your 'while not done' construct seems a bit awkward--I'll show you a more standard idiom below. I'm also putting everything into functions--it makes for cleaner, more understandable code, and makes it easier to expand on this later. Finally, on to your real question--how to store your links. What you need to do is create a lits, and then add any links that you've found to that list. So, here's my quick (untested) rewrite of your script: import sys import urllib def findlinks(url): try: fp = urllib.urlopen(url) except IOError: return [] # return an empty list if we can't get a page results = [] # create an empty list to store results in while 1: # loop until something else stops us line = fp.readline() if line == "": break #if we're at end-of-file, then break out of while loop links = re.findall('href="(.*?)"', line) # I prefer using plural identifiers for lists... results = results + links # adding two lists creates a list of all items in both lists fp.close() return results input_url = sys.argv[1] # might be good to add some error checking here... found = findlinks(input_url) print "Links found in %s", input_url for item in found: print item Two things worth further comment--in your initial try/except block, you assigned an error-message string to fp if the urlopen() failed. However, when you do fp.readline() or fp.close() on that string, you'll throw another exception. It seems to me that returning an empty list is the simplest error-handling. You may want to do something else, depending on your intent. The bigger issue, though, is that you're going through the file (url) line-by-line, when there's no need to at all. The re.findall() should be able to handle strings of fairly considerable length. So you can replace that central while loop with this: text = fp.read() results = re.findall('href="(.*?)"', text) Hope that this helps! Jeff Shannon Technician/Programmer Credit International From dyoo@hkn.eecs.berkeley.edu Tue Oct 2 18:32:15 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 2 Oct 2001 10:32:15 -0700 (PDT) Subject: [Tutor] Help - Doubt of Listbox (fwd) Message-ID: Dear Glauco, Hello again! I'm somewhat unable to answer your question at the moment (I still have this project due Thursday. After Thursday, I should be ok.) It's usually better to send messages to the tutor list, so that you can get other people to look at your questions. I'll forward your question to the list. Again, my apologies! ---------- Forwarded message ---------- Date: Tue, 2 Oct 2001 09:35:53 -0300 From: Glauco Silva To: Danny Yoo Subject: Re: [Tutor] Help - Doubt of Listbox I would like to know if have any module that put directories or files in one listbox for exemple . If you have , i would like to know if you can past to me . Thank you ! Glauco ----- Original Message ----- From: Danny Yoo To: Glauco Silva Cc: Sent: Tuesday, October 02, 2001 4:12 AM Subject: Re: [Tutor] Help - Doubt of Listbox On Mon, 1 Oct 2001, Glauco Silva wrote: > Hi men , I'm new member of this list and i have a doubt of programing > in Python : Hello! By the way: it's not just men in here; we welcome all genders, nationalities, carbon-based and non-carbon-based lifeforms to Tutor. Welcome aboard! > - I would like to know how i can mount two listbox and put Directories > in the first one and files of the directories in the second listbox . We can create a Frame() that will house those two listboxes: ### >>> frame = Frame(root) >>> frame.pack() ### Not too exciting yet, since there's nothing in the frames yet. Let's add two listboxes to that frame: ### >>> dir_listbox = Listbox(frame) >>> files_listbox = Listbox(frame) >>> dir_listbox.pack() >>> files_listbox.pack() ### By this time, we should have two listboxes on-screen. That takes care of much of the GUI side of things. Now all we need to do is add things into those Listboxes. There are a few functions in the 'os' module that might be useful, as well as the 'glob' module. You can find out about both on the Library Documentation site of Python.org: http://python.org/doc/lib One thing that should be added: it sounds like you're writing a file browser of some kind. If so, you might want to see if someone has done this already, as it's quite a bit of work. There are collections of widgets from the Python Megeawidgets project: http://pmw.sourceforge.net Anyway, hope this helps. What other questions do you have? If you have more questions, please feel free to ask the list. From riddlebox@vitalogy.org Tue Oct 2 19:29:51 2001 From: riddlebox@vitalogy.org (RIDDLE BOX) Date: Tue, 2 Oct 2001 11:29:51 -0700 Subject: [Tutor] help Message-ID: <200110021829.f92ITpP25404@mail8.bigmailbox.com> Hello, I may have the been trying to do this wrong with that code, but I would like the program to look at a file and then when you are done looking at that file, I would like it to ask if you would like to look at another file, and keep asking that until you quit the program. this is my whole code right now. I hope I am on the right track. thanks for all your help I am pretty sure that my while statement is wrong but I dont know how to get it to work thanks class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text="quit", fg="blue", command=frame.quit) self.button.pack(side=RIGHT) self.second_chance = Button(frame, text="would you like to look at another file?", fg="red", command=self.second_chance) self.second_chance.pack(side=LEFT) def second_chance(self): read = raw_input("where is the file located?") inp = open(read, "r") for line in inp.readlines(): print line root = Tk() app = App(root) ------------------------------------------------------------ This Email Is Provided Free Of Charge Thanks To http://www.vitalogy.org Sponsored by: http://www.iminteractive.net Internet Solutions, web host & more! From dyoo@hkn.eecs.berkeley.edu Tue Oct 2 19:55:12 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 2 Oct 2001 11:55:12 -0700 (PDT) Subject: [Tutor] help In-Reply-To: <200110021829.f92ITpP25404@mail8.bigmailbox.com> Message-ID: On Tue, 2 Oct 2001, RIDDLE BOX wrote: > I may have the been trying to do this wrong with that code, but I > would like the program to look at a file and then when you are done > looking at that file, I would like it to ask if you would like to look > at another file, and keep asking that until you quit the program. this > is my whole code right now. I hope I am on the right track. thanks > for all your help I am pretty sure that my while statement is wrong > but I dont know how to get it to work thanks Here's a small example of doing something until the user types the word "quit". ### while 1: filename = raw_input("What file? ('quit' to quit)") if filename == 'quit': break inp = open(filename) for line in inp.readlines(): print line ### What might seem unusual about this code is that it is an infinite loop! Or, at least, it seems that way. There is one way out of the loop though: if the user types 'quit' when asked for a filename, we can "break" out of the loop. We can write this another way: ### filename = raw_input("What file? ('quit' to quit)") while filename != 'quit': inp = open(filename) for line in inp.readlines(): print line filename = raw_input("What file? ('quit' to quit)") ### In this case, we're rearranging some of the statements, but the effect is the same --- or, at least, should be the same. I haven't tested this code out at all yet. *grin* Try some while loops of your own; if you find that a while loop has gone out of control, you can press the key combination "Control-c", and that usually cancels a Python program. Good luck! From urnerk@qwest.net Tue Oct 2 20:25:00 2001 From: urnerk@qwest.net (Kirby Urner) Date: Tue, 02 Oct 2001 12:25:00 -0700 Subject: [Tutor] help In-Reply-To: References: <200110021829.f92ITpP25404@mail8.bigmailbox.com> Message-ID: <4.2.0.58.20011002122226.00a6a6a0@pop3.norton.antivirus> > >We can write this another way: > >### >filename = raw_input("What file? ('quit' to quit)") >while filename != 'quit': > inp = open(filename) > for line in inp.readlines(): > print line > filename = raw_input("What file? ('quit' to quit)") >### I agree with Danny's approach of not following you into Tk right away. The shell is already an interactive space, and if your goal is simply to dump lines of text to screen, there's no need to use anything beyond stdout. In general, I would discourage new-to-Python users from diving straight into Tk. We all like GUI widgets, but the overhead added by the cosmetic "icing on the cake" obscures the guts/internals you need to master first (i.e. baking the cake itself). Kirby From dsh8290@rit.edu Tue Oct 2 21:12:50 2001 From: dsh8290@rit.edu (dman) Date: Tue, 2 Oct 2001 16:12:50 -0400 Subject: [Tutor] Help! In-Reply-To: <005701c14aaa$f15108c0$0100a8c0@uhuihh>; from doy20@telcel.net.ve on Mon, Oct 01, 2001 at 02:57:19PM -0400 References: <005701c14aaa$f15108c0$0100a8c0@uhuihh> Message-ID: <20011002161250.A5362@harmony.cs.rit.edu> On Mon, Oct 01, 2001 at 02:57:19PM -0400, Doy wrote: | Hi i want to know if there is a way to compile a python file to a | .exe file... so everybody can run it without installing python or | NEEDING A DLL... thanks! Yeah, see py2exe or Gordon McMillan's "installer" program. It's a royal PITA though, from all the questions and discussion I've seen on various lists. Is it really so hard to install python? -D From dsh8290@rit.edu Tue Oct 2 21:40:24 2001 From: dsh8290@rit.edu (dman) Date: Tue, 2 Oct 2001 16:40:24 -0400 Subject: [Tutor] Client Server Programming In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFAA@mbtlipnt02.btlabs.bt.co.uk>; from alan.gauld@bt.com on Tue, Oct 02, 2001 at 05:21:40PM +0100 References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFAA@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20011002164024.C5362@harmony.cs.rit.edu> On Tue, Oct 02, 2001 at 05:21:40PM +0100, alan.gauld@bt.com wrote: | > First we had to write it using sockets and create our own protocol. | > This can be done and doesn't rely on any 3rd party software, but is a | > lot of work for little gain. | | Hmm, sockets are usually my default option. Unless the protocol is | very complex or the number of messages very rich(>50 say) I tend to | opt for sockets - easy to write, easy to debug and fairly performant. | 'Course security and scaleability etc are poor (or must be hand crafted)... With the first iteration of the app for lab my partner and I had a whole bunch of classes used as data for the communication. We had a class for each type of request, and a data that was then returned. There were also classes for the various error conditions that could be returned. The idea behind the many classes was to allow subclassing in the future for more advanced systems. java.io.Object[In|Out]putStream was used and each side would just check the type of the object read from the stream. When we re-wrote it to use RMI, and now CORBA the system got much simpler. We removed lots of code and most of the classes. The hard part was figuring out how to get the middleware systems up and running (the docs for rmiregistry kinda left out a few rather important details). Just so you know _why_ I have the opinion I have, and you can decide if you agree or not :-). Also, I was forgetting about xml-rpc when I wrote my previous message. -D From iamgod@cc.jyu.fi Tue Oct 2 22:05:05 2001 From: iamgod@cc.jyu.fi (=?ISO-8859-1?Q?Risto_Per=E4nen?=) Date: Wed, 3 Oct 2001 00:05:05 +0300 (EEST) Subject: [Tutor] Monty? (2.generation python) In-Reply-To: Message-ID: How do I get information of internal structures of Python. I'm fiddling with a _HUGE_ game project which uses C++ as basic/root language. As we all know, python is fantastic scripting language but everytime you create new type with it the python requires recompilations. Furthermore, I haven't ever liked doing C++ with plain C :) So I really would like to use C++ without any goddamn macros as root language with project. On the other hand, python's syntax is easy to learn but powerfull enough so it's quite obvious choise for mentor :) Can anybody help or will I be slain down by pythoneers :) Risto Peranen 040 756 94 12 iamgod@st.jyu.fi From dyoo@hkn.eecs.berkeley.edu Tue Oct 2 23:22:25 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 2 Oct 2001 15:22:25 -0700 (PDT) Subject: [Tutor] Monty? (2.generation python) In-Reply-To: Message-ID: On Wed, 3 Oct 2001, [ISO-8859-1] Risto Per=E4nen wrote: > How do I get information of internal structures of Python. I'm > fiddling with a _HUGE_ game project which uses C++ as basic/root > language. As we all know, python is fantastic scripting language but > everytime you create new type with it the python requires > recompilations. > > Furthermore, I haven't ever liked doing C++ with plain C :) So I > really would like to use C++ without any goddamn macros as root > language with project. >=20 > On the other hand, python's syntax is easy to learn but powerfull > enough so it's quite obvious choise for mentor :) >=20 > Can anybody help or will I be slain down by pythoneers :) Ah, a C/C++ programmer. We shall not shun you. Check out the Python/C API: http://www.python.org/doc/current/api/api.html as well as the Extending and Embedding Document: http://www.python.org/doc/current/ext/ext.html Both are very useful at digging at Python's internals. The best thing to do, though, is to take a look at Python source code itself, and see how they're implementing things. If you have any questions, please feel free to ask them. Although what you're asking about is something of an advanced topic, a few of us here have some experience with Python extensions. You'll also find the main comp.lang.python newsgroup useful on asking questions on Python internals. From pemrograman@telkom.net Wed Oct 3 11:54:02 2001 From: pemrograman@telkom.net (Adinda Praditya) Date: Wed, 3 Oct 2001 17:54:02 +0700 Subject: [Tutor] Client Server Programming References: <000c01c14b86$4de2e1e0$0101a8c0@workgroup> <20011002115703.F4468@harmony.cs.rit.edu> Message-ID: <001d01c14bf9$b7932be0$0101a8c0@workgroup> > > What platform do the components need to run on? How much low-level > work do you want to do, versus how much work learning and setting up a > middleware package? > I'm running Mandrake 8.0, actually i'm gonna build an LTSP (Linux Terminal Server Project) billing system for Internet Cafe. As you know, everything is running on the Server, Is socket really necessary for that? (still confuse). > For school I have had to write some trivial distributed systems. > First we had to write it using sockets and create our own protocol. > This can be done and doesn't rely on any 3rd party software, but is a > lot of work for little gain. Then we used RMI (yeah, the course is > taught with Java), and most recently CORBA. I tried out the CORBA > stuff with Python (using the orbit-python bindings on my Debian box) > and it is really cool and fairly simple to create and use distributed > objects. I recommend CORBA if you have the flexibility to choose a > good set of bindings to a good orb. > I haven't heard about CORBA, i'll check it out and i'll try it. Thank you all, Dida From dsh8290@rit.edu Tue Oct 2 23:54:14 2001 From: dsh8290@rit.edu (dman) Date: Tue, 2 Oct 2001 18:54:14 -0400 Subject: [Tutor] Python program, seg. faults and dies In-Reply-To: <200110011420.KAA10538@birds.us.itd.umich.edu>; from lsloan@umich.edu on Mon, Oct 01, 2001 at 10:20:18AM -0400 References: <200110011420.KAA10538@birds.us.itd.umich.edu> Message-ID: <20011002185414.A6956@harmony.cs.rit.edu> On Mon, Oct 01, 2001 at 10:20:18AM -0400, Lance E Sloan wrote: | | A colleague of mine was written a Python program that causes | a segmentation fault and dies under Solaris 2.6. I ran it and | got it to produce a coredump file, but I'm not sure how to get | the Python program and core file loaded into the debugger, GDB. | I've done so with C programs, but GDB says it doesn't recognize | the Python program as an executable. | | If anybody has experience with this, could you drop me a line? The python program is a "script" not an "executable" as far as gdb is concerted (it isn't ELF or a.out format). If you want to fire up gdb, use 'python' as the program, since that is really the "program" that gave the core dump. What sort of program is it? Does it use threads? Does it use a GUI from multiple threads? Does it try and modify a list or dict while iterating over it? These are some of the situations that can lead to race conditions and thus core dumps. (the list/dict modification one is hard to trigger, but I remember hearing about a patch for it) HTH, -D From jerryl@europa.com Wed Oct 3 00:00:54 2001 From: jerryl@europa.com (Jerry Lake) Date: Tue, 2 Oct 2001 16:00:54 -0700 Subject: [Tutor] homesite & python In-Reply-To: Message-ID: <000301c14b96$178738c0$0103670a@europa.com> I currently use Homesite to do the vast majority of my programming/text editing, and I'm wonder if there is a Python.scc (homesite parser) for python. it has decent syntax highlighting right now, but it doesn't recognize some things, like it will highlight "elsif", but not "elif" or at least not that I am aware of. Thanks, Jerry Lake Interface Engineering Technician From jerryl@europa.com Wed Oct 3 00:06:59 2001 From: jerryl@europa.com (Jerry Lake) Date: Tue, 2 Oct 2001 16:06:59 -0700 Subject: [Tutor] homesite & python In-Reply-To: <000301c14b96$178738c0$0103670a@europa.com> Message-ID: <000401c14b96$f12cb0a0$0103670a@europa.com> in regards to my last message, does anyone have any thoughts on Komodo ? Thanks, Jerry Lake Interface Engineering Technician -----Original Message----- From: Jerry Lake [mailto:jerryl@europa.com] Sent: Tuesday, October 02, 2001 4:01 PM To: tutor@python.org Subject: [Tutor] homesite & python I currently use Homesite to do the vast majority of my programming/text editing, and I'm wonder if there is a Python.scc (homesite parser) for python. it has decent syntax highlighting right now, but it doesn't recognize some things, like it will highlight "elsif", but not "elif" or at least not that I am aware of. Thanks, Jerry Lake Interface Engineering Technician _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From joejava@dragoncat.net Wed Oct 3 00:16:37 2001 From: joejava@dragoncat.net (Joel Ricker) Date: Tue, 2 Oct 2001 19:16:37 -0400 Subject: [Tutor] PIL Install Question Message-ID: <001901c14b98$49be3940$45814cd8@joeltklrijxxms> Hi all, I got my web hoster to agree to install PIL plus the jpeg and PNG/Zlib libraries for me so I can do image manipulation in Python. I'm in a virtual hosting environment and while the webmaster is great at maintaining accounts and the basic day to day operation of web hosting, when it comes to intricate details of Linux, he's not aware of how to do much. The first thing he tried doing for me was to install jpeg-6b. I set it up in my home directory and pointed out where it was at for him plus the basic instructions which are: ""If you are on a Unix machine, you may not need to read this file at all. Try doing ./configure make make test If that doesn't complain, do make install (better do "make -n install" first to see if the makefile will put the files where you want them). Read further if you run into snags or want to customize the code for your system."" My webmasters response: ""Hmmm...what exactly are we doing that root wouldn't have permission to do? :) Here's what I got: [root@host jpeg-6b]# ./configure bash: ./configure: Permission denied"" So my question is, why is this getting a permission denied and what can I tell to do to fix it? Thanks Joel -------------------------------------------------- There are worlds out there where the sky is burning, the seas sleep, and the rivers dream; people made of smoke, and cities made of song. Somewhere there's danger; somewhere there's injustice, and somewhere else the tea is getting cold! Come on Ace, we've got work to do! From dsh8290@rit.edu Wed Oct 3 00:32:59 2001 From: dsh8290@rit.edu (dman) Date: Tue, 2 Oct 2001 19:32:59 -0400 Subject: [Tutor] Monty? (2.generation python) In-Reply-To: ; from iamgod@cc.jyu.fi on Wed, Oct 03, 2001 at 12:05:05AM +0300 References: Message-ID: <20011002193259.C6956@harmony.cs.rit.edu> On Wed, Oct 03, 2001 at 12:05:05AM +0300, Risto Per=E4nen wrote: | How do I get information of internal structures of Python. I'm | fiddling with a _HUGE_ game project which uses C++ as basic/root | language. As we all know, python is fantastic scripting language but | everytime you create new type with it the python requires | recompilations. Furthermore, I haven't ever liked doing C++ with All you need to do is compile your extension module, and relink it (at runtime). You don't need to rebuild python itself. Python uses dlopen() to open new extension modules at run time. | plain C :) So I really would like to use C++ without any goddamn | macros as root language with project. Alex Martelli is a C++ guru (and Python guru on comp.lang.python) and really likes Boost Python for extending Python with C++. There is also swig and other tools to semi-automatically wrap your C/C++ code as a python extension module. -D From dsh8290@rit.edu Wed Oct 3 00:47:51 2001 From: dsh8290@rit.edu (dman) Date: Tue, 2 Oct 2001 19:47:51 -0400 Subject: [Tutor] PIL Install Question In-Reply-To: <001901c14b98$49be3940$45814cd8@joeltklrijxxms>; from joejava@dragoncat.net on Tue, Oct 02, 2001 at 07:16:37PM -0400 References: <001901c14b98$49be3940$45814cd8@joeltklrijxxms> Message-ID: <20011002194751.E6956@harmony.cs.rit.edu> On Tue, Oct 02, 2001 at 07:16:37PM -0400, Joel Ricker wrote: | Hi all, | | I got my web hoster to agree to install PIL plus the jpeg and PNG/Zlib | libraries for me so I can do image manipulation in Python. I'm in a virtual | hosting environment and while the webmaster is great at maintaining accounts | and the basic day to day operation of web hosting, when it comes to | intricate details of Linux, he's not aware of how to do much. | | The first thing he tried doing for me was to install jpeg-6b. I set it up | in my home directory and pointed out where it was at for him plus the basic | instructions which are: Is he using Debian? If he is try 'apt-get install python-imaging' :-). I don't know about the jpeg-6b package, but PIL is pre-packaged for a number of linux distros. | My webmaster's response: | | "" | Hmmm...what exactly are we doing that root wouldn't have permission to do? :) | | Here's what I got: | | [root@host jpeg-6b]# ./configure | bash: ./configure: Permission denied | "" ls -l ./configure I bet it isn't executable :-). chmod ugo+x ./configure will fix it. HTH, -D From joejava@dragoncat.net Wed Oct 3 01:21:04 2001 From: joejava@dragoncat.net (Joel Ricker) Date: Tue, 2 Oct 2001 20:21:04 -0400 Subject: [Tutor] PIL Install Question References: <001901c14b98$49be3940$45814cd8@joeltklrijxxms> <20011002194751.E6956@harmony.cs.rit.edu> Message-ID: <004d01c14ba1$4a19b0a0$45814cd8@joeltklrijxxms> From: "dman" : | The first thing he tried doing for me was to install jpeg-6b. I set it up : | in my home directory and pointed out where it was at for him plus the basic : | instructions which are: : : Is he using Debian? If he is try 'apt-get install python-imaging' : :-). I don't know about the jpeg-6b package, but PIL is pre-packaged : for a number of linux distros. Not sure. I can check. Is Debian a flavor of Linux? The install I'm playing with is all I found for PIL. At http://www.pythonware.com/downloads/index.htm#pil is only listed the source and three windows only installations. According to the documentation, To get JPEG support I have to install the IJG Jpeg Library and for PNG and Zip Support, I have to get and instal the Zlib library. If there are any pre-built installations or easy installs, please I'm all ears :) : | My webmaster's response: : | : | "" : | Hmmm...what exactly are we doing that root wouldn't have permission to do? :) : | : | Here's what I got: : | : | [root@host jpeg-6b]# ./configure : | bash: ./configure: Permission denied : | "" : : ls -l ./configure : : I bet it isn't executable :-). : : chmod ugo+x ./configure : So those two lines will fix it? Cool. Something I should ask in relation to this is, this isn't going to mess with the Python install as its set now is it? I'd like to avoid that since if something goes wrong, I wouldn't want to be to blame to taking out everyone else's python service :) Thanks Joel From joejava@dragoncat.net Wed Oct 3 01:42:55 2001 From: joejava@dragoncat.net (Joel Ricker) Date: Tue, 2 Oct 2001 20:42:55 -0400 Subject: [Tutor] PIL Install Question References: <001901c14b98$49be3940$45814cd8@joeltklrijxxms> <20011002194751.E6956@harmony.cs.rit.edu> Message-ID: <006401c14ba4$578fdbd0$45814cd8@joeltklrijxxms> : ls -l ./configure : : I bet it isn't executable :-). : : chmod ugo+x ./configure I figured that if that all there is to the problem, then maybe I can install it ok as it seems (at least in general testing) that I have compile permissions. I tried the following. As you can see I tried several things but none seemed to work. Of course it may be obvious to someone who isn't a linux dummy like myself :) [jricker2@host jpeg-6b]$ chmod ugo+x ./configure [jricker2@host jpeg-6b]$ ls -l ./configure -rwxr-xr-x 1 jricker2 justthef 62320 Sep 29 15:18 ./configure [jricker2@host jpeg-6b]$ ./configure bash: ./configure: No such file or directory [jricker2@host jpeg-6b]$ configure bash: configure: command not found [jricker2@host jpeg-6b]$ cd .. [jricker2@host jricker2]$ ./configure bash: ./configure: No such file or directory [jricker2@host jricker2]$ Thanks Joel From rufmetal@home.com Wed Oct 3 03:17:23 2001 From: rufmetal@home.com (Chris Keelan) Date: Tue, 2 Oct 2001 21:17:23 -0500 Subject: [Tutor] if...elif question Message-ID: <01100221172300.05461@tygesen> I know the answer is staring me right in the face, but why does this little code snippet: ## a function to convert percentages to letter grades def grades(percent): if percent < 60: return 'F' elif percent >= 60 < 70: return 'D' else: return 'A' ##test the function percent=75 mark=grades(60) print "%s percent is a grade of %s" % (percent, mark) ...produce this output: >> 75 percent is a grade of D ?!? Shouldn't the value of 75 fail the second elif test and return the 'else' value? What am I doing wrong? - Chris From ignacio@openservices.net Wed Oct 3 02:24:21 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Tue, 2 Oct 2001 21:24:21 -0400 (EDT) Subject: [Tutor] if...elif question In-Reply-To: <01100221172300.05461@tygesen> Message-ID: On Tue, 2 Oct 2001, Chris Keelan wrote: > I know the answer is staring me right in the face, but why does this little > code snippet: > > ## a function to convert percentages to letter grades > def grades(percent): > > if percent < 60: > return 'F' > > elif percent >= 60 < 70: > return 'D' > > else: > return 'A' > > ##test the function > > percent=75 > mark=grades(60) > > print "%s percent is a grade of %s" % (percent, mark) > > ...produce this output: > > >> 75 percent is a grade of D > > ?!? > > Shouldn't the value of 75 fail the second elif test and return the 'else' > value? > > What am I doing wrong? It should read "elif percent>=60 and percent<70:". As you have it, it evaluates "percent>=60" and then compares that against 70. Since the result of the first is always less than 70 (either 0 or 1), it is always true. -- Ignacio Vazquez-Abrams From ak@silmarill.org Wed Oct 3 02:23:08 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Tue, 02 Oct 2001 21:23:08 -0400 Subject: [Tutor] if...elif question In-Reply-To: <01100221172300.05461@tygesen> References: <01100221172300.05461@tygesen> Message-ID: <20011002212308.A17980@sill.silmarill.org> On Tue, Oct 02, 2001 at 09:17:23PM -0500, Chris Keelan wrote: > I know the answer is staring me right in the face, but why does this little > code snippet: > > ## a function to convert percentages to letter grades > def grades(percent): > > if percent < 60: > return 'F' > > elif percent >= 60 < 70: elif 60 <= percent < 70: > return 'D' > > else: > return 'A' > > ##test the function > > percent=75 > mark=grades(60) > > print "%s percent is a grade of %s" % (percent, mark) > > ...produce this output: > > >> 75 percent is a grade of D > > ?!? > > Shouldn't the value of 75 fail the second elif test and return the 'else' > value? What happens is first percent is compared to 60, and the result is true. then I think 60 is compared to 70, and that is always true. Just a guess, and I didn't test my code but I'm almost certain it should work fine. > > What am I doing wrong? > > - Chris > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From kalle@gnupung.net Wed Oct 3 02:28:33 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Wed, 3 Oct 2001 03:28:33 +0200 Subject: [Tutor] if...elif question In-Reply-To: <01100221172300.05461@tygesen> References: <01100221172300.05461@tygesen> Message-ID: <20011003032833.C8109@sandrew.lysator.liu.se> Disclaimer: It's late (here), please forgive any spelling errors, coding mistakes and general weirdness below. [Chris Keelan] > I know the answer is staring me right in the face, but why does this little > code snippet: > > ## a function to convert percentages to letter grades > def grades(percent): > > if percent < 60: > return 'F' > > elif percent >= 60 < 70: This is equivalent with elif (percent >= 60) and (60 < 70): elif 60 <= percent < 70: is probably what you want, this means elif (60 <= percent) and (percent < 70): Peace, Kalle -- [ Thought control, brought to you by the WIPO! ] [ http://anti-dmca.org/ http://eurorights.org/ ] From dyoo@hkn.eecs.berkeley.edu Wed Oct 3 02:31:42 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 2 Oct 2001 18:31:42 -0700 (PDT) Subject: [Tutor] if...elif question In-Reply-To: <01100221172300.05461@tygesen> Message-ID: On Tue, 2 Oct 2001, Chris Keelan wrote: > I know the answer is staring me right in the face, but why does this little > code snippet: > > ## a function to convert percentages to letter grades > def grades(percent): > > if percent < 60: > return 'F' > > elif percent >= 60 < 70: > return 'D' Ah! You probably meant to write it like this: elif 60 <= percent < 70: "If the percent is between the range of 60 and 70...". Another way to write this is: elif percent >= 60 and percent < 70: Taking a look back, my guess on the bug is that Python interpreted your condition: > elif percent >= 60 < 70: as: elif percent >= 60 and 60 < 70: One thing that will simplify your code a lot is this: if we're on the elif part of an if test, we know that the first condition must be false --- and we can take advantage of this: ### if percent < 60: return 'f' elif percent < 70: return 'd' else: return 'a' ### Hope this helps! From kalle@gnupung.net Wed Oct 3 02:33:17 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Wed, 3 Oct 2001 03:33:17 +0200 Subject: [Tutor] if...elif question In-Reply-To: References: <01100221172300.05461@tygesen> Message-ID: <20011003033317.D8109@sandrew.lysator.liu.se> [Ignacio Vazquez-Abrams] > On Tue, 2 Oct 2001, Chris Keelan wrote: > > elif percent >= 60 < 70: > It should read "elif percent>=60 and percent<70:". As you have it, it > evaluates "percent>=60" and then compares that against 70. Since the result > of the first is always less than 70 (either 0 or 1), it is always true. It does? I thought python special-cased here and evaluated it as ((percent >= 60) and (60 < 70)) Same result, anyway. Peace, Kalle -- [ Thought control, brought to you by the WIPO! ] [ http://anti-dmca.org/ http://eurorights.org/ ] From ignacio@openservices.net Wed Oct 3 02:39:05 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Tue, 2 Oct 2001 21:39:05 -0400 (EDT) Subject: [Tutor] if...elif question In-Reply-To: <20011003033317.D8109@sandrew.lysator.liu.se> Message-ID: On Wed, 3 Oct 2001, Kalle Svensson wrote: > [Ignacio Vazquez-Abrams] > > On Tue, 2 Oct 2001, Chris Keelan wrote: > > > elif percent >= 60 < 70: > > It should read "elif percent>=60 and percent<70:". As you have it, it > > evaluates "percent>=60" and then compares that against 70. Since the result > > of the first is always less than 70 (either 0 or 1), it is always true. > > It does? I thought python special-cased here and evaluated it as > ((percent >= 60) and (60 < 70)) Huh. So it does. My mistake. -- Ignacio Vazquez-Abrams From dyoo@hkn.eecs.berkeley.edu Wed Oct 3 03:13:57 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 2 Oct 2001 19:13:57 -0700 (PDT) Subject: [Tutor] if...elif question In-Reply-To: <20011003033317.D8109@sandrew.lysator.liu.se> Message-ID: On Wed, 3 Oct 2001, Kalle Svensson wrote: > [Ignacio Vazquez-Abrams] > > On Tue, 2 Oct 2001, Chris Keelan wrote: > > > elif percent >= 60 < 70: > > It should read "elif percent>=60 and percent<70:". As you have it, it > > evaluates "percent>=60" and then compares that against 70. Since the result > > of the first is always less than 70 (either 0 or 1), it is always true. > > It does? I thought python special-cased here and evaluated it as > ((percent >= 60) and (60 < 70)) > > Same result, anyway. [WARNING WARNING: If you're starting out with Python, please avoid this message. I was just curious to see how Python actually understood the expression "percent >= 60 < 70".] I've always wanted to play with the Python disassembler, and now's finally an opportunity to try it out. We can use the disassembler to show exactly how Python interprets our programs, almost at the "atomic" level: ### >>> import dis >>> def mycmp(x): ... return x >= 60 < 70 ... >>> dis.dis(mycmp) 0 SET_LINENO 1 3 SET_LINENO 2 6 LOAD_FAST 0 (x) 9 LOAD_CONST 1 (60) 12 DUP_TOP 13 ROT_THREE 14 COMPARE_OP 5 (>=) 17 JUMP_IF_FALSE 10 (to 30) 20 POP_TOP 21 LOAD_CONST 2 (70) 24 COMPARE_OP 0 (<) 27 JUMP_FORWARD 2 (to 32) >> 30 ROT_TWO 31 POP_TOP >> 32 RETURN_VALUE 33 LOAD_CONST 0 (None) 36 RETURN_VALUE >>> def mycmp2(x): ... return x >= 60 and 60 < 70 ... >>> dis.dis(mycmp2) 0 SET_LINENO 1 3 SET_LINENO 2 6 LOAD_FAST 0 (x) 9 LOAD_CONST 1 (60) 12 COMPARE_OP 5 (>=) 15 JUMP_IF_FALSE 10 (to 28) 18 POP_TOP 19 LOAD_CONST 1 (60) 22 LOAD_CONST 2 (70) 25 COMPARE_OP 0 (<) >> 28 RETURN_VALUE 29 LOAD_CONST 0 (None) 32 RETURN_VALUE ### Wow. After staring at: http://python.org/doc/current/lib/bytecodes.html for a few minutes, I think I sorta understand what this is doing. Yes, Python does make a special case when it sees 'a <= b < c', since we can see that the output of the first is different from the second in many details. It feels like the first example is much more complicated compared to the second, at least in terms the byte-compiled code length. The first, for example, makes its stack dance around a lot with ROTations here and there. But I can see why it goes through all the hoops of DUPlicating and ROTating elements in its internal stack --- it's all there to make sure that a <= b < c and z <= b and b < c behave differently in Python. In the first case, Python will evaluate 'b' only once. In the second case, 'b' can be evaluated twice. What the first case is doing by "dup"licating is trying to avoid recomputing 'b'. For example: ### >>> def return10(): ... print "hello" ... return 10 ... >>> 1 <= return10() <= 100 hello 1 >>> 1 <= return10() and return10() <= 100 hello hello 1 ### A somewhat silly example, but still sorta neat in a perverse way. *grin* From shalehperry@home.com Wed Oct 3 03:41:10 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Tue, 02 Oct 2001 19:41:10 -0700 (PDT) Subject: [Tutor] if...elif question In-Reply-To: <01100221172300.05461@tygesen> Message-ID: > > percent=75 > mark=grades(60) > > print "%s percent is a grade of %s" % (percent, mark) > > ...produce this output: > >>> 75 percent is a grade of D > Nobody else mentioned this but ..... you set 'percent' to 75, then pass a value of 60 to grades() -- instead of using the percent variable. the 'percent' variable in the function grades() is local to that function and the external value you set has no affect on it. From rob@jam.rr.com Wed Oct 3 04:34:43 2001 From: rob@jam.rr.com (Rob Andrews) Date: Tue, 2 Oct 2001 22:34:43 -0500 Subject: [Tutor] homesite & python In-Reply-To: <000401c14b96$f12cb0a0$0103670a@europa.com> References: <000301c14b96$178738c0$0103670a@europa.com> Message-ID: <3BBA4103.29575.454E7@localhost> On 2 Oct 2001, at 16:06, Jerry Lake wrote: > in regards to my last message, > does anyone have any thoughts on > Komodo ? > I like it, but I think it could run slow on a Cray. Rob From rufmetal@home.com Wed Oct 3 06:01:38 2001 From: rufmetal@home.com (Chris Keelan) Date: Wed, 3 Oct 2001 00:01:38 -0500 Subject: [Tutor] if...elif question In-Reply-To: References: Message-ID: <01100300013103.05461@tygesen> On Tue, 02 Oct 2001, Danny Yoo wrote: > Ah! You probably meant to write it like this: > > elif 60 <= percent < 70: Yes! How did you know ;o) > One thing that will simplify your code a lot is this: if we're on the elif > part of an if test, we know that the first condition must be false --- and > we can take advantage of this: That's great advice. Thanks! > > ### > if percent < 60: return 'f' > elif percent < 70: return 'd' > else: return 'a' > ### > > Hope this helps! Sure does. - Chris From dsh8290@rit.edu Wed Oct 3 05:19:46 2001 From: dsh8290@rit.edu (dman) Date: Wed, 3 Oct 2001 00:19:46 -0400 Subject: [Tutor] PIL Install Question In-Reply-To: <004d01c14ba1$4a19b0a0$45814cd8@joeltklrijxxms>; from joejava@dragoncat.net on Tue, Oct 02, 2001 at 08:21:04PM -0400 References: <001901c14b98$49be3940$45814cd8@joeltklrijxxms> <20011002194751.E6956@harmony.cs.rit.edu> <004d01c14ba1$4a19b0a0$45814cd8@joeltklrijxxms> Message-ID: <20011003001946.C10273@harmony.cs.rit.edu> On Tue, Oct 02, 2001 at 08:21:04PM -0400, Joel Ricker wrote: | From: "dman" | | : | The first thing he tried doing for me was to install jpeg-6b. I set it | up | : | in my home directory and pointed out where it was at for him plus the | basic | : | instructions which are: | : | : Is he using Debian? If he is try 'apt-get install python-imaging' | : :-). I don't know about the jpeg-6b package, but PIL is pre-packaged | : for a number of linux distros. | | Not sure. I can check. Is Debian a flavor of Linux? Yes. If the file /etc/debian-version exists, then it is a debian system. There is something similar in /etc for RedHat boxes, but I don't know what it is called. | The install I'm playing with is all I found for PIL. At | http://www.pythonware.com/downloads/index.htm#pil is only listed the source | and three windows only installations. According to the documentation, To | get JPEG support I have to install the IJG Jpeg Library and for PNG and Zip | Support, I have to get and instal the Zlib library. | | If there are any pre-built installations or easy installs, please I'm all | ears :) That depends on the linux distro being used. If it is an rpm-based system (Debian is not) you can probably find a package on rpmfind.net. (All the Debian packages are on debian.org and can easily be in stalled with apt-get) | : | My webmaster's response: | : | | : | "" | : | Hmmm...what exactly are we doing that root wouldn't have permission to | do? :) | : | | : | Here's what I got: | : | | : | [root@host jpeg-6b]# ./configure | : | bash: ./configure: Permission denied | : | "" | : | : ls -l ./configure | : | : I bet it isn't executable :-). | : | : chmod ugo+x ./configure | : | | So those two lines will fix it? Cool. It should, if I am guessing the problem correctly. | Something I should ask in relation to this is, this isn't going to mess with | the Python install as its set now is it? I'd like to avoid that since if | something goes wrong, I wouldn't want to be to blame to taking out everyone | else's python service :) You can install it in your home directory, as long as you don't hit your quota. ./configure --prefix=$HOME make make install You will then need to add $HOME/ to your PYTHONPATH environment variable for python to find the modules, but that isn't a problem. I'm not sure what is causing the errors you posted in your other mail. Maybe try running "bash ./configure" instead of just "./configure". HTH, -D From urnerk@qwest.net Wed Oct 3 07:17:16 2001 From: urnerk@qwest.net (Kirby Urner) Date: Tue, 02 Oct 2001 23:17:16 -0700 Subject: [Tutor] Python Tutorial for Math Teachers In-Reply-To: <20011003001946.C10273@harmony.cs.rit.edu> References: <004d01c14ba1$4a19b0a0$45814cd8@joeltklrijxxms> <001901c14b98$49be3940$45814cd8@joeltklrijxxms> <20011002194751.E6956@harmony.cs.rit.edu> <004d01c14ba1$4a19b0a0$45814cd8@joeltklrijxxms> Message-ID: <4.2.0.58.20011002231249.00a6b220@pop3.norton.antivirus> Here's a little tutorial I posted for math teachers, using the challenge of programming a Fraction class -- something to use as an on-ramp, in the context of the Python-endowed math classroom (something we'll be seeing more of, I expect): http://www.mathforum.com/epigone/math-learn/starcrumderm Kirby From joejava@dragoncat.net Wed Oct 3 07:22:50 2001 From: joejava@dragoncat.net (Joel Ricker) Date: Wed, 3 Oct 2001 02:22:50 -0400 Subject: [Tutor] PIL Install Question References: <001901c14b98$49be3940$45814cd8@joeltklrijxxms> <20011002194751.E6956@harmony.cs.rit.edu> <004d01c14ba1$4a19b0a0$45814cd8@joeltklrijxxms> <20011003001946.C10273@harmony.cs.rit.edu> Message-ID: <008901c14bd3$d4862bb0$45814cd8@joeltklrijxxms> From: "dman" : | Not sure. I can check. Is Debian a flavor of Linux? : : Yes. If the file /etc/debian-version exists, then it is a debian : system. There is something similar in /etc for RedHat boxes, but I : don't know what it is called. The /etc/redhat-release file contained the information "Redhat 5.1 (Manhattan)". I check rpmfind and found these rpms: python-imaging-1.1.2-3mdk Python's own image processing library linux/ia64 linux/i586 linux/i586 python-imaging-1.1.2-1mdk Python's own image processing library linux/alpha python-imaging-1.1.1-2mdk Python's own image processing library Linux/ppc I'm thinking that none of these apply to the version of Redhat I'm using correct? I looked up by Vendor and found only about dozen rpms for Redhat 5.1. Thanks Joel From sampatel@cs.rmit.edu.au Wed Oct 3 08:04:28 2001 From: sampatel@cs.rmit.edu.au (Samir Patel) Date: Wed, 3 Oct 2001 17:04:28 +1000 (EST) Subject: Fwd: [Tutor] html programming ??? In-Reply-To: Message-ID: hi Jeff shannon, thanx for your help and i actually implement the things u told me to do and also i have tried to add links which i am getting to a Queue .... now another problem of mine is that i have to call this function recursively becoz i want to find links inside the links i have already found and this to a depth of 3 so how does recursion work in python ???? anyway thanx for your help samir On Wed, 3 Oct 2001, Samir Patel wrote: > > > > >From: "Jeff Shannon" > >To: tutor@python.org > >Subject: [Tutor] html programming ??? > >Date: Tue, 02 Oct 2001 09:50:23 -0700 > > > > > hi all, > > > i am trying to write python script which takes a url and opens that page > > > ...then i am trying to grab all the links present in that page and want > > > to put that links in a data structure..... > > > now my problem is that how do i use a data structure and how should i put > > > this links into that..... > > > >Hi Samir > > > >A few minor pointers. First, the re module is probably more powerful than what you need. It will certainly work, but > you could do much the > >same thing with string.find(), which is much simpler. However, I'll keep the re in place in my example below, so that > this change doesn't > >obscure the other changes I'm making. Also, your 'while not done' construct seems a bit awkward--I'll show you a more > standard idiom > >below. I'm also putting everything into functions--it makes for cleaner, more understandable code, and makes it > easier to expand on this > >later. Finally, on to your real question--how to store your links. What you need to do is create a lits, and then add > any links that > >you've found to that list. > > > >So, here's my quick (untested) rewrite of your script: > > > >import sys > >import urllib > > > >def findlinks(url): > > try: > > fp = urllib.urlopen(url) > > except IOError: > > return [] # return an empty list if we can't get a page > > > > results = [] # create an empty list to store results in > > > > while 1: # loop until something else stops us > > line = fp.readline() > > if line == "": > > break #if we're at end-of-file, then break out of while loop > > links =re.findall('href="https://www.safeweb.com/o/_o(410):_win(1):_w:_base(http://lw3fd.law3.hotmail.msn.com/cgi-bin/dasp/EN/):_bs > http://lw3fd.law3.hotmail.msn.com/cgi-bin/dasp/EN/):(.*?)"', line) # I prefer using plural identifiers for lists... > > results = results + links # adding two lists creates a list of all items in both lists > > > > fp.close() > > return results > > > > > > > >input_url = sys.argv[1] # might be good to add some error checking here... > >found = findlinks(input_url) > > > >print "Links found in %s", input_url > >for item in found: > > print item > > > > > >Two things worth further comment--in your initial try/except block, you assigned an error-message string to fp if the > urlopen() failed. > >However, when you do fp.readline() or fp.close() on that string, you'll throw another exception. It seems to me that > returning an empty > >list is the simplest error-handling. You may want to do something else, depending on your intent. > > > >The bigger issue, though, is that you're going through the file (url) line-by-line, when there's no need to at all. > The re.findall() should > >be able to handle strings of fairly considerable length. So you can replace that central while loop with this: > > > > text = fp.read() > > results =re.findall('href="https://www.safeweb.com/o/_o(410):_win(1):_w:_base(http://lw3fd.law3.hotmail.msn.com/cgi-bin/dasp/EN/):_bs > http://lw3fd.law3.hotmail.msn.com/cgi-bin/dasp/EN/):(.*?)"', text) > > > >Hope that this helps! > > > > > >Jeff Shannon > >Technician/Programmer > >Credit International > > > > > > > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > _____________________________________________________________________________________________________________________________ > Get your FREE download of MSN Explorer at http://explorer.msn.com > > From jgregorio@qwest.net Wed Oct 3 09:12:21 2001 From: jgregorio@qwest.net (Josh Gregorio) Date: Wed, 3 Oct 2001 01:12:21 -0700 Subject: [Tutor] Question on Functions Message-ID: <003001c14be3$21495d00$6a9ca1d8@computer> This is a multi-part message in MIME format. ------=_NextPart_000_002D_01C14BA8.7408B080 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I am not sure I understand how to properly use functions (or when to use = them). Suppose you had some code like this: x =3D 1 y =3D 2 def add(a,b): c =3D a + b print c add(x,y) print x,y Is there a way to store the result of a+b into a variable that is = accessible outside of the function? Could you, for instance, add x and = y, print the result c, and then update x to equal the result of x + y = (from within a function)?=20 Thank you, Josh=20 PS Could anyone recommend some good exercises to do to get more = practice/understanding? ------=_NextPart_000_002D_01C14BA8.7408B080 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I am not sure I understand how to properly use = functions=20 (or when to use them). Suppose you had some code like this:
 
x =3D 1
y =3D 2
 
def add(a,b):
   c =3D a + b
   print c
 
 
add(x,y)
 
print x,y
 
Is there a way to store the result of = a+b into a=20 variable that is accessible outside of the function? Could you, for = instance,=20 add x and y, print the result c, and then update x to equal the result = of x + y=20 (from within a function)?
 
Thank you,
Josh
 
PS Could anyone recommend some good exercises to = do to get=20 more practice/understanding?
------=_NextPart_000_002D_01C14BA8.7408B080-- From ak@silmarill.org Wed Oct 3 09:03:27 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Wed, 03 Oct 2001 04:03:27 -0400 Subject: [Tutor] Question on Functions In-Reply-To: <003001c14be3$21495d00$6a9ca1d8@computer> References: <003001c14be3$21495d00$6a9ca1d8@computer> Message-ID: <20011003040327.A19736@sill.silmarill.org> On Wed, Oct 03, 2001 at 01:12:21AM -0700, Josh Gregorio wrote: > I am not sure I understand how to properly use functions (or when to use them). Suppose you had some code like this: > > x = 1 > y = 2 > > def add(a,b): > c = a + b > print c > > > add(x,y) > > print x,y > > Is there a way to store the result of a+b into a variable that is accessible outside of the function? Could you, for instance, add x and y, print the result c, and then update x to equal the result of x + y (from within a function)? Certainly..: def add(a, b): return a + b result = add(x, y) print result # prints 3 In general, functions are used to package some repeating algorithm up. Let's say you have this: print "x + z is", x + z print "y + a is", y + a [100 more lines of the sort] Now, you could make a function add() like the one above, to print the result. In this case there's not much point to it because it's as easy to type x + z as add(x, z), even easier. What if you had a function that spanned 30 lines and you needed its output for different values in 100 places in your program? You could either write one 30 line function and call it from 100 places (totalling 130 lines) or you could reproduce the same logic on each of the 100 lines, giving you 100 * 30 - 3000 lines. One problem here is that it's a lot more typing, another problem is that if you want to change the function (like you found a bug or something), it's much easier to change it in one places instead of changing it in 100 places. Typically, make a function if you see that there's a few places in your program that use the same algorithm logic and you can save yourself typing effort by using a function. > > Thank you, > Josh > > PS Could anyone recommend some good exercises to do to get more practice/understanding? -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From jgregorio@qwest.net Wed Oct 3 10:00:45 2001 From: jgregorio@qwest.net (Josh Gregorio) Date: Wed, 3 Oct 2001 02:00:45 -0700 Subject: [Tutor] Question on Functions References: <003001c14be3$21495d00$6a9ca1d8@computer> <20011003040327.A19736@sill.silmarill.org> Message-ID: <001301c14be9$e3f482c0$6a9ca1d8@computer> Thank you. I didn't really understand how to use return until now. Josh ----- Original Message ----- From: Andrei Kulakov To: Sent: Wednesday, October 03, 2001 1:03 AM Subject: Re: [Tutor] Question on Functions > On Wed, Oct 03, 2001 at 01:12:21AM -0700, Josh Gregorio wrote: > > I am not sure I understand how to properly use functions (or when to use them). Suppose you had some code like this: > > > > x = 1 > > y = 2 > > > > def add(a,b): > > c = a + b > > print c > > > > > > add(x,y) > > > > print x,y > > > > Is there a way to store the result of a+b into a variable that is accessible outside of the function? Could you, for instance, add x and y, print the result c, and then update x to equal the result of x + y (from within a function)? > > Certainly..: > > def add(a, b): > return a + b > > result = add(x, y) > > print result # prints 3 > > In general, functions are used to package some repeating algorithm up. > Let's say you have this: > > print "x + z is", x + z > print "y + a is", y + a > [100 more lines of the sort] > > Now, you could make a function add() like the one above, to print the > result. In this case there's not much point to it because it's as easy to > type x + z as add(x, z), even easier. What if you had a function that > spanned 30 lines and you needed its output for different values in 100 > places in your program? You could either write one 30 line function and > call it from 100 places (totalling 130 lines) or you could reproduce the > same logic on each of the 100 lines, giving you 100 * 30 - 3000 lines. One > problem here is that it's a lot more typing, another problem is that if > you want to change the function (like you found a bug or something), it's > much easier to change it in one places instead of changing it in 100 > places. > > Typically, make a function if you see that there's a few places in your > program that use the same algorithm logic and you can save yourself typing > effort by using a function. > > > > > Thank you, > > Josh > > > > PS Could anyone recommend some good exercises to do to get more practice/understanding? > > -- > Cymbaline: intelligent learning mp3 player - python, linux, console. > get it at: cy.silmarill.org > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From iamgod@cc.jyu.fi Wed Oct 3 14:05:37 2001 From: iamgod@cc.jyu.fi (=?ISO-8859-1?Q?Risto_Per=E4nen?=) Date: Wed, 3 Oct 2001 16:05:37 +0300 (EEST) Subject: [Tutor] Extenting python with C++ without recompilations? Message-ID: On Tue, 2 Oct 2001 tutor-request@python.org wrote: > | everytime you create new type with it the python requires > | recompilations. Furthermore, I haven't ever liked doing C++ with > > All you need to do is compile your extension module, and relink it (at > runtime). You don't need to rebuild python itself. Python uses > dlopen() to open new extension modules at run time. What I ment was if your functions/procedures need to return new types, which will be returned in multiple others extension modules, the other modules does need to recompiled, doesn't it? I mean how could C system use something without proper interface? Sure I could include all header of other previous extension modules in my new modules but still many extension modules need to recompiled if I something in early make modules is changed. With C++ I could simple make an interface and changing implementions of memberfunctions (aka methods) without need for recompilation of other modules. Furthermore I would like to make scripting language which is more based on events and is more restricted than python. Yet making methods internally with classes sound cool for speed - but it does spend huge amounts of memory. > | plain C :) So I really would like to use C++ without any goddamn > | macros as root language with project. > > Alex Martelli is a C++ guru (and Python guru on comp.lang.python) and > really likes Boost Python for extending Python with C++. There is > also swig and other tools to semi-automatically wrap your C/C++ code > as a python extension module. Hmm, I'll check out his work iamgod@st.jyu.fi From wilson@visi.com Wed Oct 3 14:25:17 2001 From: wilson@visi.com (Timothy Wilson) Date: Wed, 3 Oct 2001 08:25:17 -0500 (CDT) Subject: [Tutor] rounding up to the nearest penny Message-ID: Hi everyone, I gave my students a programmig assignment (see http://www.isd197.org/sibley/cs/icp/assignments/loancalc_html for specifics) and discovered one small feature that I couldn't figure out (at least easily). My impression is that when doing financial calculations dollar amounts are often rounded up to the nearest penny. The round function does a true round to the nearest penny. The ceil function doesn't appear to work with floats. >>> >>> amount = 1.342 >>> round(amount, 2) 1.34 >>> import math >>> math.ceil(amount) 2.0 Any suggestions? -Tim -- Tim Wilson | Visit Sibley online: | Check out: Henry Sibley HS | http://www.isd197.org | http://www.zope.com W. St. Paul, MN | | http://slashdot.org wilson@visi.com | | http://linux.com From David_Reed@CINFIN.com Wed Oct 3 14:37:23 2001 From: David_Reed@CINFIN.com (Reed, David) Date: Wed, 3 Oct 2001 09:37:23 -0400 Subject: [Tutor] it says I can ask questions. Message-ID: I'm a looking for a module and method that will allow me to make Windows 2000 shortcut files or (lnk). Do you have documentation or reference as to how to do this? David M Reed - Cincinnati Financial Corp (513) 870-2000 x4380 email: david_reed@cinfin.com From kalle@gnupung.net Wed Oct 3 15:14:24 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Wed, 3 Oct 2001 16:14:24 +0200 Subject: [Tutor] Question on Functions In-Reply-To: <003001c14be3$21495d00$6a9ca1d8@computer> References: <003001c14be3$21495d00$6a9ca1d8@computer> Message-ID: <20011003161424.A8876@sandrew.lysator.liu.se> [Josh Gregorio] [snip question already answered by others] > PS Could anyone recommend some good exercises to do to get more > practice/understanding? Check out Useless Python: http://www.lowerstandard.com/python/ It's a collection of code and excercises maintained by Rob Andrews, a regular here on the tutor list. Peace, Kalle -- [ Thought control, brought to you by the WIPO! ] [ http://anti-dmca.org/ http://eurorights.org/ ] From arcege@speakeasy.net Wed Oct 3 15:15:02 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Wed, 3 Oct 2001 10:15:02 -0400 Subject: [Tutor] rounding up to the nearest penny In-Reply-To: ; from wilson@visi.com on Wed, Oct 03, 2001 at 08:25:17AM -0500 References: Message-ID: <20011003101502.A980@speakeasy.net> On Wed, Oct 03, 2001 at 08:25:17AM -0500, Timothy Wilson wrote: > My impression is that when doing financial calculations dollar amounts = are > often rounded up to the nearest penny. The round function does a true > round to the nearest penny. The ceil function doesn't appear to work wi= th > floats. The ceil function is based on the C library function. From the manpage: The ceil() function rounds x upwards to the nearest inte=AD ger, returning that value as a double. Since a lot of applications don't use ceil a lot, and there is a standard math solution to get non-whole unit answers, it probably wasn't deemed necessary to get add that functionality. >>> amount =3D 1.342 >>> hundredths =3D 100 >>> import math >>> math.ceil(amount * hundredths) / hundredths 1.35 >>> Unfortunately, you can't get the string formats to do the ceiling function, but they can do the floor function. Good luck. -Arcege --=20 +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | | Ailment info: http://www.speakeasy.org/~arcege/michaelwatch.html | From kromag@nsacom.net Wed Oct 3 18:03:39 2001 From: kromag@nsacom.net (kromag@nsacom.net) Date: Wed, 3 Oct 2001 10:03:39 -0700 (PDT) Subject: [Tutor] Character-mode Text Editor? Message-ID: <200110031703.f93H3dY29398@pop.nsacom.net> Has anyone ever created a character mode text editor in python? Just something simple like pico or edit. From joejava@dragoncat.net Wed Oct 3 17:40:20 2001 From: joejava@dragoncat.net (Joel Ricker) Date: Wed, 3 Oct 2001 12:40:20 -0400 Subject: [Tutor] PIL Install Question References: <001901c14b98$49be3940$45814cd8@joeltklrijxxms> <20011002194751.E6956@harmony.cs.rit.edu> Message-ID: <001d01c14c2a$17303fe0$22a0d6d1@joeltklrijxxms> : Is he using Debian? If he is try 'apt-get install python-imaging' : :-). I don't know about the jpeg-6b package, but PIL is pre-packaged : for a number of linux distros. Hey dman and alll, As I was re-reading through the messages looking for some clue as to something else I could try. (bash ./configure didn't work: [jricker2@host jpeg-6b]$ bash ./configure : command not found : command not found : command not found : command not found : command not found '/configure: syntax error near unexpected token `do '/configure: ./configure: line 65: `do [jricker2@host jpeg-6b]$ ) and I ran across the above. Are you saying that it could be that they are possibly already done in distribution and I don't need to install? There are a series of .pyc files in a directory called PIL. Well there is only one way to find out and try it right :) I just assumed that you would have to compile it since they give you the source to compile with or is the source provided for your own amusement/additions? Thanks for all the help Joel From jday@digitas.com Wed Oct 3 18:54:36 2001 From: jday@digitas.com (John Day) Date: Wed, 3 Oct 2001 10:54:36 -0700 Subject: [Tutor] Can someone please explain a Stack Trace Message-ID: <30F1F222A8E31740ADE51928C0CE93B48123@EXSFO1.digitas.com> I am trying to learn "verbage" and one item I don't understand fully is "Stack Trace". I have gone through numerous tutorials, yet, it is not working for me. Please help. Thank You. From arcege@speakeasy.net Wed Oct 3 20:16:04 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Wed, 3 Oct 2001 15:16:04 -0400 Subject: [Tutor] Can someone please explain a Stack Trace In-Reply-To: <30F1F222A8E31740ADE51928C0CE93B48123@EXSFO1.digitas.com>; from jday@digitas.com on Wed, Oct 03, 2001 at 10:54:36AM -0700 References: <30F1F222A8E31740ADE51928C0CE93B48123@EXSFO1.digitas.com> Message-ID: <20011003151604.A1150@speakeasy.net> On Wed, Oct 03, 2001 at 10:54:36AM -0700, John Day wrote: > I am trying to learn "verbage" and one item I don't understand fully is > "Stack Trace". I have gone through numerous tutorials, yet, it is not > working for me. Please help. Thank You. This gets into what a "stack" is and how function calls are handled in basic programming. A stack is a LIFO (Last-In-First-Out) data structure. Each item "pushed" onto a stack is the first item "popped" off; imagine a stack of books, where you may only remove one from the top. Each call to a function is similar: a function is called, and the related data gets pushed onto a stack. Each function will have local values and where in the program the next instruction will be (so when we return from a function we know were to continue). When a program fails (not just Python, but other languages as well), you can get a stack trace, which shows each function that is currently executing, and where they are in the program. For example, lets say we have the following program: def a(): w2 = "spam" return 1/0 # force an exception to be raised def b(w1): print a() def c(w3=5): print b c() b("what?") Now if we execute this, we'll have an exception raised. $ python /tmp/t1.py Traceback (innermost last): File "/tmp/t1.py", line 8, in ? b("what?") File "/tmp/t1.py", line 6, in b print a() File "/tmp/t1.py", line 3, in a return 1/0 # force an exception to be raised ZeroDivisionError: integer division or modulo The trace(-back) shows that first we called "b" with the string "what?" as the argument. It was called at line 8 in the main part ("?") of the file (/tmp/t1.py). Inside function b, the statement "print a()" forced a function call to "a", with no arguments at line 6 in the file. And in a, we ran the statement "return 1/0" which caused the exception. There is no trace of the function "c" because it already completed, so its data was "popped" off the stack. I hope this helps you understand better. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | | Ailment info: http://www.speakeasy.org/~arcege/michaelwatch.html | From ignacio@openservices.net Wed Oct 3 20:17:50 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Wed, 3 Oct 2001 15:17:50 -0400 (EDT) Subject: [Tutor] Can someone please explain a Stack Trace In-Reply-To: <30F1F222A8E31740ADE51928C0CE93B48123@EXSFO1.digitas.com> Message-ID: On Wed, 3 Oct 2001, John Day wrote: > I am trying to learn "verbage" and one item I don't understand fully is > "Stack Trace". I have gone through numerous tutorials, yet, it is not > working for me. Please help. Thank You. A program in Python, C/C++, sh, etc. contains function calls. When a function call is made, the program has to know where the call was made so that it can get back when a return or end-of-function is reached. A "stack" is a LIFO (last in, first out) data structure. As such, it "pushes" items down and returns and removes the topmost when "popped". The location where every function call has been made is pushed onto the stack, and a "stack trace" is simply the list of locations contained in that stack. -- Ignacio Vazquez-Abrams From ak@silmarill.org Wed Oct 3 20:17:41 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Wed, 03 Oct 2001 15:17:41 -0400 Subject: [Tutor] rounding up to the nearest penny In-Reply-To: References: Message-ID: <20011003151741.B21962@sill.silmarill.org> On Wed, Oct 03, 2001 at 08:25:17AM -0500, Timothy Wilson wrote: > Hi everyone, > > I gave my students a programmig assignment (see > http://www.isd197.org/sibley/cs/icp/assignments/loancalc_html for > specifics) and discovered one small feature that I couldn't figure out (at > least easily). > > My impression is that when doing financial calculations dollar amounts are > often rounded up to the nearest penny. The round function does a true > round to the nearest penny. The ceil function doesn't appear to work with > floats. > > >>> > >>> amount = 1.342 > >>> round(amount, 2) > 1.34 > >>> import math > >>> math.ceil(amount) > 2.0 > > Any suggestions? > > -Tim Since this question was answered already, I'll comment on usage of floats for currency - this is frowned upon! Floats are inexact. Currency is something you want to be exact with :P. Instead, as far as I understand, people use integers - they convert the whole sum to pennies and assign it to an integer or have two integers, for pennies and dollars. > > -- > Tim Wilson | Visit Sibley online: | Check out: > Henry Sibley HS | http://www.isd197.org | http://www.zope.com > W. St. Paul, MN | | http://slashdot.org > wilson@visi.com | | http://linux.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From shalehperry@home.com Wed Oct 3 20:35:43 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Wed, 03 Oct 2001 12:35:43 -0700 (PDT) Subject: [Tutor] Can someone please explain a Stack Trace In-Reply-To: Message-ID: > > A "stack" is a LIFO (last in, first out) data structure. As such, it "pushes" > items down and returns and removes the topmost when "popped". > > The location where every function call has been made is pushed onto the > stack, > and a "stack trace" is simply the list of locations contained in that stack. > The best real world example I have seen explained uses dinner plates. You start with a plate. The next night you decide not to do dishes and place that plate on the previous one. This continues until it is time to do dishes. You then remove the plates in reverse order (as Ignacio says, Last In, First out). A "stack trace" would be equivalent to looking through the plate for what you had for dinner two nights ago. You would remove enough plates one after the other to get back to the right plate. From dsh8290@rit.edu Wed Oct 3 20:49:12 2001 From: dsh8290@rit.edu (dman) Date: Wed, 3 Oct 2001 15:49:12 -0400 Subject: [Tutor] PIL Install Question In-Reply-To: <008901c14bd3$d4862bb0$45814cd8@joeltklrijxxms>; from joejava@dragoncat.net on Wed, Oct 03, 2001 at 02:22:50AM -0400 References: <001901c14b98$49be3940$45814cd8@joeltklrijxxms> <20011002194751.E6956@harmony.cs.rit.edu> <004d01c14ba1$4a19b0a0$45814cd8@joeltklrijxxms> <20011003001946.C10273@harmony.cs.rit.edu> <008901c14bd3$d4862bb0$45814cd8@joeltklrijxxms> Message-ID: <20011003154912.A11159@harmony.cs.rit.edu> On Wed, Oct 03, 2001 at 02:22:50AM -0400, Joel Ricker wrote: | From: "dman" | | : | Not sure. I can check. Is Debian a flavor of Linux? | : | : Yes. If the file /etc/debian-version exists, then it is a debian | : system. There is something similar in /etc for RedHat boxes, but I | : don't know what it is called. | | The /etc/redhat-release file contained the information "Redhat 5.1 | (Manhattan)". 5.1!? Wow, that's old. Your admin really should upgrade, but stay away from the 7.x series (broken libc and non-release quality & binary incompatible compiler). | I check rpmfind and found these rpms: | | python-imaging-1.1.2-3mdk Python's own image processing library | linux/ia64 linux/i586 linux/i586 | python-imaging-1.1.2-1mdk Python's own image processing library | linux/alpha | python-imaging-1.1.1-2mdk Python's own image processing library | Linux/ppc | | | I'm thinking that none of these apply to the version of Redhat I'm using | correct? Right, they're for Mandrake (another rpm-based distro). | I looked up by Vendor and found only about dozen rpms for Redhat | 5.1. What version of python does RH5.1 have? Try this out : http://pathfinder.scar.utoronto.ca/~csca57/PIL_python.html ftp://sponge.ssec.wisc.edu/pub/pydl/python-imaging-1.1-1.i386.rpm I have no idea if that rpm is binary compatible with 5.1 or not, but give it a try. The worst thing that could happend is it doesn't work (ie it doesn't run or python crashes when you try and use it) and the admin needs to remove the package. -D From dsh8290@rit.edu Wed Oct 3 20:53:16 2001 From: dsh8290@rit.edu (dman) Date: Wed, 3 Oct 2001 15:53:16 -0400 Subject: [Tutor] PIL Install Question In-Reply-To: <001d01c14c2a$17303fe0$22a0d6d1@joeltklrijxxms>; from joejava@dragoncat.net on Wed, Oct 03, 2001 at 12:40:20PM -0400 References: <001901c14b98$49be3940$45814cd8@joeltklrijxxms> <20011002194751.E6956@harmony.cs.rit.edu> <001d01c14c2a$17303fe0$22a0d6d1@joeltklrijxxms> Message-ID: <20011003155314.B11159@harmony.cs.rit.edu> On Wed, Oct 03, 2001 at 12:40:20PM -0400, Joel Ricker wrote: | | : Is he using Debian? If he is try 'apt-get install python-imaging' | : :-). I don't know about the jpeg-6b package, but PIL is pre-packaged | : for a number of linux distros. | | Hey dman and alll, | | As I was re-reading through the messages looking for some clue as to | something else I could try. (bash ./configure didn't work: | | [jricker2@host jpeg-6b]$ bash ./configure | : command not found | : command not found | : command not found | : command not found | : command not found | '/configure: syntax error near unexpected token `do | '/configure: ./configure: line 65: `do | [jricker2@host jpeg-6b]$ | | ) and I ran across the above. Hmm, bash doesn't like the script. Either the script is buggy, or it is corrupted, or that version of bash is old and/or buggy and maybe missing some new features. | Are you saying that it could be that they are possibly already done | in distribution and I don't need to install? There are a series of | .pyc files in a directory called PIL. Well there is only one way to | find out and try it right :) I just assumed that you would have to | compile it since they give you the source to compile with or is the | source provided for your own amusement/additions? Normally for Unix-like systems the source is provided because it is too hard for a developer to make a binary release for all the various combinations of Unis OSes, hardware platforms, and library versions. For most stuff it isn't too hard to compile anyways. For Linux, the binary packages are frequently under the control/management/responsibility of the distribution. For example, RH (or others who want to volunteer) maintain the RPMs for RH and the Debian Developers maintain the .deb for Debian. For most stuff there are binary packages available, but it various from distro to distro and all releases of a distro may not be supported. (Debian has, unless I am mistaken, the most packages available when compared with any other linux distro) -D From alan.gauld@bt.com Wed Oct 3 22:14:35 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 3 Oct 2001 22:14:35 +0100 Subject: [Tutor] if...elif question Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFAD@mbtlipnt02.btlabs.bt.co.uk> > ## a function to convert percentages to letter grades > def grades(percent): > if percent < 60: > return 'F' > elif percent >= 60 < 70: To Python this looks like: else: if percent >= (60 < 70): which looks like in your case if 75 >= 1 # 1 => true To get what you want you need two tests: elif (percent >= 60) and (percent < 70): You may not need the parens but they help to make it obvious to both the reader and to python exactly what you want 'and'ed... Its all to do with a thing called operator precedence which is explained on my (now restored) web tutor in the Simple Sequences topic. And in full detail in the Python documentation. HTH, Alan G. http://www.crosswinds.net/~agauld/ From alan.gauld@bt.com Wed Oct 3 22:22:15 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 3 Oct 2001 22:22:15 +0100 Subject: [Tutor] if...elif question Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFAE@mbtlipnt02.btlabs.bt.co.uk> > > elif percent >= 60 < 70: > evaluates "percent>=60" and then compares that against 70. Hmm, yes, you're right since the >= and < have the same operator precedence it would evaluate the >= first since its leftmost. So my earlier answer is wrong in detail but right in principle. Apologies for any slight confusion it may have caused - the fix was OK tho'. To make some some amends I'll cite the page in the manuals with the full precedence list to save anyone looking for it... $PYTHON/Doc/ref/summary.html Alan g From ignacio@openservices.net Wed Oct 3 22:35:09 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Wed, 3 Oct 2001 17:35:09 -0400 (EDT) Subject: [Tutor] if...elif question In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFAE@mbtlipnt02.btlabs.bt.co.uk> Message-ID: On Wed, 3 Oct 2001 alan.gauld@bt.com wrote: > > > elif percent >= 60 < 70: > > evaluates "percent>=60" and then compares that against 70. > > Hmm, yes, you're right since the >= and < have the same operator > precedence it would evaluate the >= first since its leftmost. > > So my earlier answer is wrong in detail but right in principle. > Apologies for any slight confusion it may have caused > - the fix was OK tho'. > > To make some some amends I'll cite the page in the manuals > with the full precedence list to save anyone looking for it... > > $PYTHON/Doc/ref/summary.html Actually, if you dig around some more, you'll find that it does special-case it. http://www.python.org/doc/current/ref/comparisons.html -- Ignacio Vazquez-Abrams From alan.gauld@bt.com Wed Oct 3 22:34:52 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 3 Oct 2001 22:34:52 +0100 Subject: [Tutor] if...elif question Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFAF@mbtlipnt02.btlabs.bt.co.uk> > elif 60 <= percent < 70: > > "If the percent is between the range of 60 and 70...". Another way to > write this is: > > elif percent >= 60 and percent < 70: > Wow! Just when I think I'm getting to know Python something new bites me. I never knew Python could do comparisons like that - in fact I don't think I know of any other programming language I've used that did it... OTOH that may be because I always parenthesize comparisons from years of being bitten by C... Once again in penance I cite the doc page reference: $PYTHON/Doc/ref/comparisons.html What a language :-) Alan g From kromag@nsacom.net Thu Oct 4 01:02:29 2001 From: kromag@nsacom.net (kromag@nsacom.net) Date: Wed, 3 Oct 2001 17:02:29 -0700 (PDT) Subject: [Tutor] The same question I always ask.... Message-ID: <200110040002.f9402TY27577@pop.nsacom.net> ***WARNING: WHINING AND SNIVELING AHEAD!***** I don't know what is wrong with me, but I can't seem to get substitution. This is why I quit trying to learn c. I know that thousands of people do this every day, but for some reason it escapes me, especially when trying to do sql statements. I am trying to insert text into a database. ---------begin script------------ import string import gadfly connection=gadfly.gadfly("bbs","\windows\desktop") cursor=connection.cursor() final=open('\windows\desktop\final.txt','w') bogus='' try: while 1: rant= """%s""" % raw_input() bogus=bogus+ '12' + rant finally: cursor.execute("insert into messages(mess) values %s %(bogus)") connection.commit() final.write(bogus) final.close() ------end script--------- cursor.execute("insert into messages(mess) values %s, %(bogus)") always gives me some variant of: >pythonw -u editor.py Traceback (most recent call last): File "editor.py", line 12, in ? cursor.execute("insert into messages(mess) values %s %(bogus)") File "c:python20kwpgadfly.py", line 322, in execute cs = self.commands = sql.DoParse1(statement, context) File "c:python20kwpkjParser.py", line 1175, in DoParse1 return self.DoParse(String, Context, DoReductions)[0] File "c:python20kwpkjParser.py", line 1167, in DoParse ParseResult = ParseOb.GO() File "c:python20kwpkjParser.py", line 832, in GO self.DoOneReduction() File "c:python20kwpkjParser.py", line 725, in DoOneReduction tokenVal = Stream.getmember() File "c:python20kwpkjParser.py", line 562, in getmember (Token,skip) = self.LexDict.Token(self.String, self.Position) File "c:python20kwpkjParser.py", line 427, in Token raise LexTokenError, "Lexical token not found "+info LexTokenError: Lexical token not found near :: 's(mess) values '*'%s %(bogus)' >Exit code: 1 Trust me, I have tried every form of '%s' %(bogus) that I can think of. The logic of it just flies over my head. Every time I think I have it figured out, it bites me. I have read "learning python" to tatters..... Sorry, but constant failure takes it's toll! :-) Any help would be appreciated, wholeheartedly. From ignacio@openservices.net Wed Oct 3 22:52:59 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Wed, 3 Oct 2001 17:52:59 -0400 (EDT) Subject: [Tutor] The same question I always ask.... In-Reply-To: <200110040002.f9402TY27577@pop.nsacom.net> Message-ID: On Wed, 3 Oct 2001 kromag@nsacom.net wrote: > cursor.execute("insert into messages(mess) values %s %(bogus)") Try '"insert into messages(mess) values '%s'" % (bogus,)' instead (without the outside single quotes, of course). -- Ignacio Vazquez-Abrams From shalehperry@home.com Wed Oct 3 22:52:29 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Wed, 03 Oct 2001 14:52:29 -0700 (PDT) Subject: [Tutor] The same question I always ask.... In-Reply-To: <200110040002.f9402TY27577@pop.nsacom.net> Message-ID: Head hurts. reminds me of helping fellow students through their first programming class. Let's start clean. >> foo = 'text' >> print foo text >> person = 'Sean' >> print "%s's %s." % (person, foo) Sean's text. >> table = 'SecretTable' >> sql_command = "from %s where name = \"%s\" do this" % (table, person) >> sql(sql_command) From alan.gauld@bt.com Wed Oct 3 22:52:13 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 3 Oct 2001 22:52:13 +0100 Subject: [Tutor] it says I can ask questions. Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFB1@mbtlipnt02.btlabs.bt.co.uk> > I'm a looking for a module and method that will allow me to > make Windows > 2000 shortcut files or (lnk). Do you have documentation or > reference as to > how to do this? Use the winall COM extensions to access the WSH Filesystem objects. They include shortcut objects. See Hammonds win32 O'Reilly book for more on using WSH from Python. Also see the WSH documentation (search MSDN if its not on your PC) for how to use the relevant COM objects once instantiated. Alan G From jeff@ccvcorp.com Wed Oct 3 23:03:18 2001 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed, 03 Oct 2001 15:03:18 -0700 Subject: Fwd: [Tutor] html programming ??? References: Message-ID: <3BBB8B25.FB665324@ccvcorp.com> > From: Samir Patel > > hi Jeff shannon, > thanx for your help and i actually implement the things u told me to do > and also i have tried to add links which i am getting to a Queue .... > > now another problem of mine is that i have to call this function > recursively becoz i want to find links inside the links i have already > found and this to a depth of 3 so how does recursion work in python ???? > Recursion is pretty simple--you just call a function from within itself. The main thing to watch for is that you really do have something that will limit the depth of the recursion. Python has a limit to how deep it can recurse, but 3 levels deep is no problem at all. In this case, I'd use the findlinks() function we've created, as-is, and wrap that into a recursive function, something like this: def scanpage(url, depth=3, maxindent=None): linklist = findlinks(url) if maxindent == None: maxindent = depth indent = " " * (maxindent - depth) # this will let us progressively indent printouts from deeper levels print "%s URL -> %s:" % (indent, url) if depth > 1: for link in linklist: scanpage(link, depth - 1, maxindent) Note that this function doesn't save the found links for later use, it just prints them. If you want to save them, you'll need to find some way of keeping track of them. If you don't care which page a given link came from, you can just append them all to some global list. If you *do* care, then you could probably find some way to use nested lists, or tuples of (link, source page), or perhaps a dictionary using links as keys and source page as values, or... any number of different and potentially arbitrarily complicated schemes. :) Assuming that this simple form is fine, you can use it like so: scanpage("www.somedomain.com/index.html") This will run the function using the default depth of 3. It will then call itself on each link it find, but use a depth of 2. Each of *those* links will be called using a depth of 1. The links found at that depth will then *not* be searched further. Note that if you decide that you don't want to use a depth of 3, you can call directly with whatever depth you like, such as: scanpage("www.somedomain.com/index.html", 5) Hope that helps... Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Wed Oct 3 23:31:12 2001 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed, 03 Oct 2001 15:31:12 -0700 Subject: [Tutor] The same question I always ask.... References: Message-ID: <3BBB91B0.74F28EAE@ccvcorp.com> > From: > Ignacio and Sean have already pointed out the string-substitution error, so I won't repeat that, but there's a couple of other things here to watch out for: > connection=gadfly.gadfly("bbs","\windows\desktop") ..... > final=open('\windows\desktop\final.txt','w') Here, and in your open() call below, you have strings containing backslashes. Python is interpreting these as escape sequences. In order to prevent this, you need to either escape the backslashes by doubling them ("\\windows\\desktop"), or else use raw strings (r"\windows\desktop") to explicitly tell Python not to treat them as escapes. > bogus='' Now, here, you're setting bogus to be an empty string, and then later... > try: > while 1: > rant= """%s""" % raw_input() > bogus=bogus+ ' Here, you are setting bogus to be that empty string, plus ' -- this is not a well-formed statement. I think that Python would parse this as adding another empty string (terminating the string at the newline). So you're trying to insert an empty string into your db, so even if you succeed, it's probably not going to do much good. ;) I'm also not sure what your while loop is intended to accomplish, or how you ever break out of it, or why you've got a try: block with no except: or finally: .... so maybe there's other stuff here that you've left out? Hope that this helps clarify things... Jeff Shannon Technician/Programmer Credit International From james2dope@yahoo.com Thu Oct 4 02:17:07 2001 From: james2dope@yahoo.com (james middendorff) Date: Wed, 3 Oct 2001 18:17:07 -0700 (PDT) Subject: [Tutor] help Message-ID: <20011004011707.50628.qmail@web13902.mail.yahoo.com> --0-2056993066-1002158227=:49067 Content-Type: text/plain; charset=us-ascii hello, I am making a sore attempt at a text reader, as my first major project while I am learning how to program, and I have a few questions, my first question would be, I have actually pasted my code and my question below read = raw_input("Type the full name and path of the file you want to open ") # I need to find an error message in case there is no file where you think this is question #1 inp = open(read, "r") for line in inp.readlines(): print line my second question: is there anyway I can also write to these files? and my last one: is there some kind of way to be able to use this to open a .doc file? or even to get a .rtf file to open the way its supposed to look? thanks for the help "I would kill everyone in this room for a drop of sweet beer." ----Homer Simpson---- --------------------------------- Do You Yahoo!? NEW from Yahoo! GeoCities - quick and easy web site hosting, just $8.95/month. Yahoo! by Phone. --0-2056993066-1002158227=:49067 Content-Type: text/html; charset=us-ascii

hello,

I am making a sore attempt at a text reader, as my first major project while I am learning how to program, and I have a few questions,

my first question would be, I have actually pasted my code and my question below

read = raw_input("Type the full name and path of the file you want to open ")

 # I need to find an error message in case there is no file where you think this is question #1
inp = open(read, "r")
for line in inp.readlines():
    print line

my second question: is there anyway I can also write to these files?

and my last one: is there some kind of way to be able to use this to open a .doc file? or even to get a .rtf file to open the way its supposed to look?

thanks for the help



"I would kill everyone in this room
for a drop of sweet beer."
----Homer Simpson----



Do You Yahoo!?
NEW from Yahoo! GeoCities - quick and easy web site hosting, just $8.95/month. Yahoo! by Phone. --0-2056993066-1002158227=:49067-- From ak@silmarill.org Thu Oct 4 02:32:36 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Wed, 03 Oct 2001 21:32:36 -0400 Subject: [Tutor] help In-Reply-To: <20011004011707.50628.qmail@web13902.mail.yahoo.com> References: <20011004011707.50628.qmail@web13902.mail.yahoo.com> Message-ID: <20011003213235.A23691@sill.silmarill.org> On Wed, Oct 03, 2001 at 06:17:07PM -0700, james middendorff wrote: > > hello, > > I am making a sore attempt at a text reader, as my first major project while I am learning how to program, and I have a few questions, > > my first question would be, I have actually pasted my code and my question below > > read = raw_input("Type the full name and path of the file you want to open ") > > # I need to find an error message in case there is no file where you think this is question #1 > inp = open(read, "r") You could put it in a try/except block. Let's first find out what exception it would raise: >>> open("somefile") Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'somefile' okay.. now we know the exception.. try: inp = open(read) # 'r' is assumed by default except IOError: print "No such file" sys.exit() > for line in inp.readlines(): > print line > > my second question: is there anyway I can also write to these files? Yeah.. Let's say you want to write a file "my_file.txt" with text "TEST": f = open("my_file.txt", "w") f.write("TEST\n") # \n for newline > > and my last one: is there some kind of way to be able to use this to open a .doc file? or even to get a .rtf file to open the way its supposed to look? doc is proprietory, so opening one involves a lot of guesswork and good old trial-and-error. It sounds like this is above your head and will be for quite some time :-). I'm not exactly sure about rtf.. I think it's the same deal. > > thanks for the help > > > "I would kill everyone in this room > for a drop of sweet beer." > ----Homer Simpson---- > > > --------------------------------- > Do You Yahoo!? > NEW from Yahoo! GeoCities - quick and easy web site hosting, just $8.95/month. Yahoo! by Phone. -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From scott@griffitts.com Thu Oct 4 03:37:04 2001 From: scott@griffitts.com (Scott Griffitts) Date: Wed, 03 Oct 2001 21:37:04 -0500 Subject: [Tutor] htmllib, formatter and results as a string Message-ID: I'm trying to take a html file and format it in plain text (with some other formatting thrown in - see below). The code below gets me pretty close: import htmllib, formatter w = formatter.DumbWriter() f = formatter.AbstractFormatter(w) file = open('C://test//test.html') p = htmllib.HTMLParser(f) p.feed(file.read()) p.close() file.close() But I want to do some additional formatting. The p.feed(file.read()) part of the code is (to my newbie understanding) sending the result to stdout. I would like to catch it as a string so I can perform some further tweaking. How do I do that? Thanks, Scott From dyoo@hkn.eecs.berkeley.edu Thu Oct 4 07:02:16 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 3 Oct 2001 23:02:16 -0700 (PDT) Subject: [Tutor] homesite & python In-Reply-To: <000401c14b96$f12cb0a0$0103670a@europa.com> Message-ID: On Tue, 2 Oct 2001, Jerry Lake wrote: > in regards to my last message, does anyone have any thoughts on Komodo > ? I've heard that it's quite nice, as long as your have a relatively recent computer. I've seen the interactive regular expression writer, and it's very cool. It makes designing regular expressions less of a guessing game, and the system as a whole looks very nice. From dyoo@hkn.eecs.berkeley.edu Thu Oct 4 07:36:32 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 3 Oct 2001 23:36:32 -0700 (PDT) Subject: [Tutor] if...elif question In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFAF@mbtlipnt02.btlabs.bt.co.uk> Message-ID: On Wed, 3 Oct 2001 alan.gauld@bt.com wrote: > > elif 60 <= percent < 70: > > > > "If the percent is between the range of 60 and 70...". Another way to > > write this is: > > > > elif percent >= 60 and percent < 70: > > > > Wow! Just when I think I'm getting to know Python something new bites me. > I never knew Python could do comparisons like that - in fact I don't > think I know of any other programming language I've used that did it... > OTOH that may be because I always parenthesize comparisons from years > of being bitten by C... Things will get very interesting when Python 2.2 comes out of beta... http://www.amk.ca/python/2.2/ Especially the fact that we'll soon be able to do this: ### print 'look ma, no readlines' for line in open('hello.txt'): print line ### and do other fun stuff that we previously said was bad syntax... *grin* From dyoo@hkn.eecs.berkeley.edu Thu Oct 4 07:47:58 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 3 Oct 2001 23:47:58 -0700 (PDT) Subject: [Tutor] bsddb - mystery wrapped in enigma In-Reply-To: <200110010618.f916I4Y16888@pop.nsacom.net> Message-ID: On Sun, 30 Sep 2001 kromag@nsacom.net wrote: > I have been scouring the earth for a good tutorial on the bsddb module. Is > there anything (in print or otherwise) lurking about that might help? > > I am trying to extract information from an existing berkeley db file > (sleepycat). Have you gotten a reply yet? The documentation at: http://python.org/doc/lib/bsddb-objects.html has a small example on how to open and use a bsddb object. From what I can tell, it doesn't look too different than a dictionary (with a few enhancements.) Some people have written an enhanced bsddb that should be backward compatible: http://pybsddb.sourceforge.net/ and it looks like they have more documentation on how to working with it! http://pybsddb.sourceforge.net/bsddb3.html They even have a specialized mailing list on bsddb issues: http://lists.sourceforge.net/mailman/listinfo/pybsddb-users Hope this helps! From dyoo@hkn.eecs.berkeley.edu Thu Oct 4 07:52:29 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 3 Oct 2001 23:52:29 -0700 (PDT) Subject: [Tutor] Help - Doubt of Listbox In-Reply-To: Message-ID: On Mon, 1 Oct 2001, Glauco Silva wrote: > - Directories in the first one and files of the directories in the > second listbox . Hi Glauco, Just checking up and seeing how far you've gotton. Have you been able to get the directory list working yet? From dyoo@hkn.eecs.berkeley.edu Thu Oct 4 08:06:24 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 4 Oct 2001 00:06:24 -0700 (PDT) Subject: [Tutor] htmllib, formatter and results as a string [StringIO] In-Reply-To: Message-ID: On Wed, 3 Oct 2001, Scott Griffitts wrote: > I'm trying to take a html file and format it in plain text (with some other > formatting thrown in - see below). The code below gets me pretty close: > > import htmllib, formatter > > w = formatter.DumbWriter() Hmmm.. I believe that the DumbWriter always prints out to "standard output". Let me check. http://www.python.org/doc/lib/writer-impls.html Ah! According to the documentation, we can give DumbWriter() a file to write its output to. By default, it will print to stdout, but we can tell it to write somewhere else. There's a very nice class called StringIO() that makes a string look very much like a file: http://www.python.org/doc/lib/module-StringIO.html so we can tie all this together as: ### import StringIO, htmllib, formatter my_stringio = StringIO.StringIO() ## make an instance of this ## file-like string thing w = formatter.DumbWriter(my_stringio) f = formatter.AbstractFormatter(w) file = open('C://test//test.html') ## not sure if you have to double ## up forward slashes... but it ## doesn't hurt according to ## POSIX standards. p = htmllib.HTMLParser(f) p.feed(file.read()) ## Everything else stays the p.close() ## same... but... file.close() content = my_stringio.getvalue() ## Here's the interesting bit! ### > But I want to do some additional formatting. The p.feed(file.read()) > part of the code is (to my newbie understanding) sending the result to > stdout. I would like to catch it as a string so I can perform some > further tweaking. How do I do that? If we hadn't been able to give that StringIO file object to the DumbWriter, we can still do somethng: we can redirect standard output to a file of our choice, like this: ### import sys, StringIO my_stringio = StringIO.StringIO() sys.stdout = my_stringio ## redirect stdout to be our string file print "Hello world, do you see this?" sys.stdout = sys.__stdout__ ## set it back to the original stdout print "Here's what we captured from stdout:", my_stringio.getvalue() ### This is a bit hacky, but it is sometimes necessary. None of Python's standard library should force us to use this hack... so if you find something that does, tell us about it, and we'll complain. *grin* Either way, StringIO is a lot of fun to play with. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Thu Oct 4 08:07:59 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 4 Oct 2001 00:07:59 -0700 (PDT) Subject: [Tutor] Help - Doubt of Listbox In-Reply-To: Message-ID: On Wed, 3 Oct 2001, Danny Yoo wrote: > On Mon, 1 Oct 2001, Glauco Silva wrote: > > > - Directories in the first one and files of the directories in the > > second listbox . > > Hi Glauco, > > Just checking up and seeing how far you've gotton. Have you been able to ^^^^^^ ### dyoo@einfall:/usr/local/src/linux-2.4.10$ wordnet gotton No information available for noun gotton No information available for verb gotton No information available for adj gotton No information available for adv gotton ### Nuts. *grin* Sorry about the typo, I mean "gotten". From dyoo@hkn.eecs.berkeley.edu Thu Oct 4 08:19:15 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 4 Oct 2001 00:19:15 -0700 (PDT) Subject: [Tutor] Can someone please explain a Stack Trace In-Reply-To: Message-ID: On Wed, 3 Oct 2001, Sean 'Shaleh' Perry wrote: > A "stack" is a LIFO (last in, first out) data structure. As such, it > "pushes" items down and returns and removes the topmost when "popped". It's actually very easy to play around with something "stacklike": Python lists can be treated as stacks, if we slightly rename some things: ### >>> def makeStack(): ... return [] ... >>> def push(stack, element): ... """Push an element onto the stack.""" ... stack.append(element) ... >>> def pop(stack): ... """Pop off the first element of the stack.""" ... return stack.pop() ... >>> s = makeStack() >>> push(s, 1) >>> push(s, 2) >>> push(s, 'three') >>> pop(s) 'three' >>> pop(s) 2 >>> pop(s) 1 ### > The best real world example I have seen explained uses dinner plates. > You start with a plate. The next night you decide not to do dishes > and place that plate on the previous one. This continues until it is > time to do dishes. You then remove the plates in reverse order (as > Ignacio says, Last In, First out). The book "Godel Escher Bach", by Douglas Hofstadler, has a pretty neat example of stacks in his "Little Harmonic Labyrinth" and Chapter 5 (Recursive Structures and Processes". Very fun reading, especially for budding programmers. *grin* From dyoo@hkn.eecs.berkeley.edu Thu Oct 4 08:25:59 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 4 Oct 2001 00:25:59 -0700 (PDT) Subject: [Tutor] Can someone please explain a Stack Trace In-Reply-To: Message-ID: > The book "Godel Escher Bach", by Douglas Hofstadler, has a pretty neat ^^^^^^^^^^ Oh my gosh, I'm misspelling everything today. Sorry about that; I'm typing this on my laptop, as my main computer is down. The author's last name is "Hofstadter", not "Hofstadler". From sgriffitts@fwsymphony.org Thu Oct 4 16:08:43 2001 From: sgriffitts@fwsymphony.org (Scott Griffitts) Date: Thu, 04 Oct 2001 10:08:43 -0500 Subject: [Tutor] htmllib, formatter and results as a string [StringIO] Message-ID: >import sys, StringIO >my_stringio =3D StringIO.StringIO() >sys.stdout =3D my_stringio ## redirect stdout to be our string file >print "Hello world, do you see this?" >sys.stdout =3D sys.__stdout__ ## set it back to the original stdout >print "Here's what we captured from stdout:", my_stringio.getvalue() >### >This is a bit hacky, but it is sometimes necessary. None of Python's >standard library should force us to use this hack... so if you find >something that does, tell us about it, and we'll complain. *grin* >Either way, StringIO is a lot of fun to play with. Hope this helps! Thanks, Danny. StringIO works like a charm and should help me with some = other problems I was having. -Scott From israel@lith.com Thu Oct 4 16:45:45 2001 From: israel@lith.com (Israel Evans) Date: Thu, 4 Oct 2001 08:45:45 -0700 Subject: [Tutor] A fun, instant gratification playground for Python... Blender! Message-ID: I don't know how many of you already know this, and I apologize if this seems to be old news, but it's new to me and it's gotten me all gooey inside! I was looking around for a 3d modeling and animation package I could afford and I found one that fits the budget most exquisitely: Blender. It's free. It produces good stuff. It comes with an integrated game creation and playback mode. The interface is quite different than any of the other Highend and very expensive packages I use at work (Maya, Softimage, 3ds Max, and Lightwave), but after using it for a while, I think I'll get used to it. The coolest thing of all is that I can use Python to script all manner of things in Blender. I've only just started but the possibilities are really attractive. I can even code games in Blender using Python. Very cool! If you are interested check out www.blender.nl . The python specific stuff can be found in the resources section or under www.blender.nl/python . Have fun with it! ~Israel~ enthusiastic newbie pythonista... From sasoft@gmx.de Thu Oct 4 23:07:21 2001 From: sasoft@gmx.de (Stefan Antoni) Date: Thu, 4 Oct 2001 18:07:21 -0400 Subject: [Tutor] homesite & python In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Wed, Oct 03, 2001 at 11:02:16PM -0700 References: <000401c14b96$f12cb0a0$0103670a@europa.com> Message-ID: <20011004180721.A9246@cruciatuz.de> On Wed, Oct 03, 2001 at 11:02:16PM -0700, Danny Yoo wrote: > > in regards to my last message, does anyone have any thoughts on Komodo > > ? > > I've seen the interactive regular expression writer, and it's very cool. > It makes designing regular expressions less of a guessing game, and the > system as a whole looks very nice. That sounds interesting, what _is_ this regex writer? Or better: how does it work? (a link would be enough :)) -- best regards, Stefan Antoni From cccomputer@c4.com Thu Oct 4 10:15:38 2001 From: cccomputer@c4.com (CC Computer Consulting Co.) Date: Thu, 4 Oct 2001 09:15:38 Subject: [Tutor] THE MAIL KING - ah13 Message-ID: IF YOU USE DIRECT MAIL IN YOUR BUSINESS -- THEN READ ON. OTHERWISE, JUST DELETE THIS MESSAGE. Make Every Letter Count - Get Every Letter Opened! Did you know?? According to experts, today's deluged direct mail recipient throws away 26% to 88% of all their "junk mail" UNOPENED! Would you like to increase your responses by an average of 3 to 6 times?? If you would (and who wouldn't) just REPLY to this message and we will e-mail you more details. CC Computer Consulting Co. PS: If you prefer a response by "snail mail", include your name and mailing address in your reply. **************************************** This email is sent in compliance with our strict anti-abuse regulations. This is not SPAM. This message was sent to you because you, or someone using your email address, requested information, sent or posted to our system, Opt-in, FFA site, Classifieds, web site or email box If you would like to be removed from this list, e-mail to or click on: Remove@cccomputer.zzn.com *************************************** ah13 From shalehperry@home.com Thu Oct 4 17:12:49 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Thu, 04 Oct 2001 09:12:49 -0700 (PDT) Subject: [Tutor] A fun, instant gratification playground for Python.. In-Reply-To: Message-ID: Some additional info/clarifications. Blender is without cost, but it is closed source. And yes the user interface takes lots of getting used to. In fact if you do not use it regularly it can be quite daunting. However blender is one of the great 3d creation environments. Big plus -- no ray tracing! It is hella fast. From dyoo@hkn.eecs.berkeley.edu Thu Oct 4 17:41:50 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 4 Oct 2001 09:41:50 -0700 (PDT) Subject: [Tutor] THE MAIL KING - ah13 In-Reply-To: Message-ID: On Thu, 4 Oct 2001, CC Computer Consulting Co. wrote: > Make Every Letter Count - Get Every Letter Opened! You've Got Things Reversed And You Have Things Cased. This is a common mistake if you're a newbie to the English language, so we'll forgive you for now. This is Tutor though; we cannot help you learn about word order and the proper role of capitalization. We can help you with Python though. You probably meant to say "Make a count of every letter": ### def histogram(thing): counts = {} for element in thing: counts[element] = counts.get(element, 0) + 1 return counts ### This function is pretty useful if you're trying to make sense out of "nonsense" --- cryptographers often use histograms to drive their guesses of what a message really contains. Here's an example that shows how this histogram function works: ### >>> histogram("> Make Every Letter Count - Get Every Letter Opened!") {'>': 1, 'y': 2, 'v': 2, 't': 6, 'u': 1, 'r': 4, 'p': 1, 'n': 2, 'o': 1, '-': 1, 'k': 1, 'a': 1, 'd': 1, 'e': 10, ' ': 9, '!': 1, 'O': 1, 'L': 2, 'M': 1, 'G': 1, 'E': 2, 'C': 1} ### There. Sense out of nonsense. From lkvam@venix.com Thu Oct 4 18:01:45 2001 From: lkvam@venix.com (Lloyd Kvam) Date: Thu, 04 Oct 2001 13:01:45 -0400 Subject: [Tutor] THE MAIL KING - ah13 References: Message-ID: <3BBC95F9.1C50ED1E@venix.com> I had already lodged a SPAM complaint about this email when I saw your "reply" come through. I searched through my trash to make sure it had not been a plea for help. It's too bad the spammer doesn't actually read the tutor list. He might get enlightened. Danny Yoo wrote: > > On Thu, 4 Oct 2001, CC Computer Consulting Co. wrote: > > > Make Every Letter Count - Get Every Letter Opened! > > You've Got Things Reversed And You Have Things Cased. This is a common > mistake if you're a newbie to the English language, so we'll forgive you > for now. This is Tutor though; we cannot help you learn about word order > and the proper role of capitalization. > > We can help you with Python though. You probably meant to say "Make a > count of every letter": > > ### > def histogram(thing): > counts = {} > for element in thing: > counts[element] = counts.get(element, 0) + 1 > return counts > ### > > This function is pretty useful if you're trying to make sense out of > "nonsense" --- cryptographers often use histograms to drive their guesses > of what a message really contains. > > Here's an example that shows how this histogram function works: > > ### > >>> histogram("> Make Every Letter Count - Get Every Letter Opened!") > {'>': 1, 'y': 2, 'v': 2, 't': 6, 'u': 1, 'r': 4, 'p': 1, 'n': 2, 'o': 1, > '-': 1, 'k': 1, 'a': 1, 'd': 1, 'e': 10, ' ': 9, '!': 1, 'O': 1, 'L': 2, > 'M': 1, 'G': 1, 'E': 2, 'C': 1} > ### > > There. Sense out of nonsense. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From lumbricus@gmx.net Thu Oct 4 17:51:31 2001 From: lumbricus@gmx.net (Joerg Woelke) Date: Thu, 4 Oct 2001 18:51:31 +0200 Subject: [Tutor] A fun, instant gratification playground for Python... Blender! In-Reply-To: ; from israel@lith.com on Thu, Oct 04, 2001 at 08:45:45AM -0700 References: Message-ID: <20011004185131.A11264@Laplace.localdomain> On Thu, Oct 04, 2001 at 08:45:45AM -0700, Israel Evans wrote: [ Blender ] > If you are interested check out www.blender.nl . > The python specific stuff can be found in the resources section or under > www.blender.nl/python . The Linux-Magazin 02/2000 contained an article about "3D-Python-Skripting in Blender". Unfortunately my Hardware doesn't get it :-(. But it was very interesting with some of examples. The listings were available at "ftp://ftp.linux-magazin.de/pub/graphics/blender/Python2.tgz". > > Have fun with it! dito > ~Israel~ > enthusiastic newbie pythonista... HTH,HAND J"o! :-) -- It is your concern when your neighbor's wall is on fire. -- Quintus Horatius Flaccus (Horace) From danny.kohn@systematik.se Thu Oct 4 18:41:49 2001 From: danny.kohn@systematik.se (Danny Kohn) Date: Thu, 4 Oct 2001 19:41:49 +0200 Subject: [Tutor] Stuck with classes Message-ID: Hi. Have the following problem that I cannot seem to figure out. class matrixPanel(wxPanel): def __init__(self, parent, id): wxPanel.__init__(self, parent, id, wxDefaultPosition, wxPyDefaultSize) def makeGrid(): self.GridSizer =3D wxFlexGridSizer( 2, 3, 1, 1 ) [...] class genGrid: def __init__(self): pass def addGen(self, panel): # Create Function table self.DescWin =3D wxGrid(...) [...] yyy.AddWindow( ...) p =3D matrixPanel(frame1, -1) gr =3D p.makeGrid gg=3DgenGrid() [?] How in earth do I pass self.GridSizer in matrixPanel to yyy? Or do I = have to do this in a nested class. I have tried that also with = disappointing results. Thanks. Danny Kohn Tel: +46 (708) 140 300 (\_/) )) ICQ: 1328817 ('.')=3D// Miau! Ham: SM=D8NBJ ( ~~~ )/ Rrrrrui! =20 `w---w=B4 From lkvam@venix.com Thu Oct 4 19:08:23 2001 From: lkvam@venix.com (Lloyd Kvam) Date: Thu, 04 Oct 2001 14:08:23 -0400 Subject: [Tutor] Stuck with classes References: Message-ID: <3BBCA597.67C6EEC8@venix.com> I don't follow what you are doing but.... gg.addGen(p) AND within the addGen method yyy.AddWindow(p.GridSizer, ...) should be proper python statements. (I don't know what gr is in your sni= ppet since there is no return from makeGrid) Danny Kohn wrote: > = > Hi. > Have the following problem that I cannot seem to figure out. > = > class matrixPanel(wxPanel): > def __init__(self, parent, id): > wxPanel.__init__(self, parent, id, wxDefaultPosition, w= xPyDefaultSize) > = > def makeGrid(): > self.GridSizer =3D wxFlexGridSizer( 2, 3, 1, 1 ) > [...] > = > class genGrid: > def __init__(self): > pass > def addGen(self, panel): > # Create Function table > self.DescWin =3D wxGrid(...) > [...] > yyy.AddWindow( ...) > = > p =3D matrixPanel(frame1, -1) > gr =3D p.makeGrid > gg=3DgenGrid() > [?] > = > How in earth do I pass self.GridSizer in matrixPanel to yyy? Or do I ha= ve to do this in a nested class. I have tried that also with disappointin= g results. > = > Thanks. > Danny Kohn Tel: +46 (708) 140 300 (\_/) )) > ICQ: 1328817 ('.')=3D// Miau! > Ham: SM=D8NBJ ( ~~~ )/ Rrrrrui! > `w---w=B4 > = > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- = Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From urnerk@qwest.net Thu Oct 4 19:08:38 2001 From: urnerk@qwest.net (Kirby Urner) Date: Thu, 04 Oct 2001 11:08:38 -0700 Subject: [Tutor] Stuck with classes In-Reply-To: Message-ID: <4.2.0.58.20011004105436.00c2e840@pop3.norton.antivirus> At 07:41 PM 10/4/2001 +0200, Danny Kohn wrote: >Hi. >Have the following problem that I cannot seem to figure out. > >class matrixPanel(wxPanel): > def __init__(self, parent, id): > wxPanel.__init__(self, parent, id, wxDefaultPosition, > wxPyDefaultSize) > > def makeGrid(): > self.GridSizer = wxFlexGridSizer( 2, 3, 1, 1 ) > [...] makeGrid should have a self parameter. wxFlexGridSizer is global to the module? >class genGrid: > def __init__(self): > pass > def addGen(self, panel): > # Create Function table > self.DescWin = wxGrid(...) > [...] > yyy.AddWindow( ...) > >p = matrixPanel(frame1, -1) >gr = p.makeGrid gr = p.makeGrid makes gr a pointer to the function, doesn't trigger the function or cause it to return anything. Use gr = p.makeGrid() if you expect a return value or want addGen to actually do something (your abbreviated code doesn't say what this might be). >gg=genGrid() >[?] > >How in earth do I pass self.GridSizer in matrixPanel to yyy? Or >do I have to do this in a nested class. I have tried that also >with disappointing results. p is your matrixPanel object (note: customary to capitalize first letter of classes, but not required of course). self.GridSizer is a property of matrixPanel objects, so p.GridSizer will be the specific value of this property for p. If you want to pass that in for use by gg (a genGrid object), just go: gg = genGrid(p.GridSizer) and in genGrid, define __init__ so that it keeps a copy of p.GridSizer as a member property, e.g. >class genGrid: > def __init__(self,gridsizer): > self.gridsizer = gridsizer Or you could even just go: gg = genGrid() gg.gridsizer = p.GridSizer Example: >>> class C: def __init__(self): pass def doit(self): print self.message >>> o = C() >>> o.message = "Hello" >>> o.doit() Hello Then, in your addGen, you can reference this value as self.gridsizer, including when passing parameters to yyy (but yyy is not defined in this class, so I don't claim to understand your larger framework, or what it is you're really doing here). Kirby From dyoo@hkn.eecs.berkeley.edu Thu Oct 4 20:14:35 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 4 Oct 2001 12:14:35 -0700 (PDT) Subject: [Tutor] Stuck with classes In-Reply-To: Message-ID: On Thu, 4 Oct 2001, Danny Kohn wrote: > class matrixPanel(wxPanel): > def __init__(self, parent, id): > wxPanel.__init__(self, parent, id, > wxDefaultPosition, wxPyDefaultSize) > > def makeGrid(): > self.GridSizer = wxFlexGridSizer( 2, 3, 1, 1 ) > [...] > > class genGrid: > def __init__(self): > pass > def addGen(self, panel): > # Create Function table > self.DescWin = wxGrid(...) > [...] > yyy.AddWindow( ...) > > p = matrixPanel(frame1, -1) > gr = p.makeGrid > gg=genGrid() > [?] > > How in earth do I pass self.GridSizer in matrixPanel to yyy? Or do I > have to do this in a nested class. I have tried that also with > disappointing results. There are several approaches we can make to pass the GridSizer of a matrixPanel off to something else. Here's one way: we can yank out the GridSizer directly from our matrixPanel: ### gridsizer = p.GridSizer ### and then slightly tweak genGrid.addGen() to take in another parameter --- not only the panel, but a GridSizer instance: ### class genGrid: def __init__(self): pass def addGen(self, panel, gridsizer): # Create Function table self.DescWin = wxGrid(...) [...] yyy.AddWindow( ...) ## and from here, we can pass ## the gridsizer over to yyy. ### I have to admit, though, that I'm not familiar enough with wxPython to know if this is an wxPythonic approach or not. *grin* Alternatively, we can pass the whole matrixPanel off to the genGrid. And there are a few other ways to get genGrid.addGen() to know about your gridsizer. This is an interesting question; please feel free to ask more questions as you design your program. Good luck to you! From gbcs1978@hotmail.com Thu Oct 4 20:30:48 2001 From: gbcs1978@hotmail.com (Glauco Silva) Date: Thu, 4 Oct 2001 16:30:48 -0300 Subject: [Tutor] Help - how to do a window Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0051_01C14CF1.ECC13980 Content-Type: multipart/alternative; boundary="----=_NextPart_001_0052_01C14CF1.ECC13980" ------=_NextPart_001_0052_01C14CF1.ECC13980 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hello everybody !! I have other doubt . I would like to know if anybody can help me . I = don't know how to do this kind of window attached . If anybody know , please help me ! Thank you ! GLAUCO ------=_NextPart_001_0052_01C14CF1.ECC13980 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hello everybody !!
 
I have other doubt . I would like to = know if=20 anybody can help me . I don't know how to do this kind of window = attached=20 .
If anybody know , please help me = !
Thank you !
 
GLAUCO
------=_NextPart_001_0052_01C14CF1.ECC13980-- ------=_NextPart_000_0051_01C14CF1.ECC13980 Content-Type: image/jpeg; name="imagem.jpg" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="imagem.jpg" /9j/4AAQSkZJRgABAQEBLAEsAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0a HBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIy MjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCALNBD8DASIA AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3 ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK U1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3 uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDvJpo7 eGSaaRI4o1Lu7sAqqOSST0AqtY6pa6j5ggMqvHjfHPA8LgHODtcA4ODg4wcH0NP1GCO60y7t5rd7 iKWF0eFGCtIpBBUEkYJ6ZyPqK5iWfWLjSNRSyudQmiHkbLm7szFOMyfv1CKsbECMAjaAxLEK24Da AdU11Cl5FaM+J5Y3lRMHlVKhjnpwXX86mrzp7XXBHFJbT3soWGdEuJLSZGjiaW03gK7mYnasxGWD nB2YAQ1ctku44bcajcaxPpW6YhoILqKUPiLYMB2uNv8Ar+XOM9seXQB2yTRyPIkciM0TbJArAlGw Dg+hwQfoRTLu6hsbOe7uX2QQRtLI+CdqqMk4HJ4FcTd2eqRC+dG1CA3N5BLcyMkkrGAWoUHbbsvz +cmG8og8An5MZrarb38vh67t9QOsXW/TXSw8iG4QvKWl4kSNmONnkAecSSM5+beKAO21DWLPTZoY bj7Q0sys6JBbSTMVXaGOEU4A3L19afDqlrPcx26mVZpI2lRJYHjJUBCT8wHTzEH1JHUEDN1Wwurz xLprwXV3aJHZ3Iee3RG5LwYUl0YDOCemfl+tYOsQa2+vahLai7VV8xI5vLdgkLfYN+zBBPCzkBCG JDbfmoA7yiuGRNTj0y3zcaxcJ9qYw+XBLCxGFAHzu8gIbeQZ/wB2cMrAKY2HZ23l+U3l+bt8x8+b uzncc/e5xnOO2MY4xQBNRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFdB4Y/5ev+Af1rn66Dwx/y9f8AAP60AdBRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQA UUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABR RRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFF FAHm99BZ3NnJDfxQS2rY3pOoZDyCMg8dcVQsrLw7psxmsLbS7WVl2F4I40YrwcZHbgflVbxz/wAi NrX/AF6P/KtbWdI8K6Sb2aXwzoCWtqrSOx0uI7UUZJ4XJ4oAd9vs/wDn7g/7+Cj7fZ/8/cH/AH8F ZNnF4fubwWlx4G0qxnaNpY0uNNtW8xVKhiDGWAwXTrj73GcHFybTvDFvLbxS+GfD6vcSGKIf2XEd zBWfH3ePlRjz6UAWvt9n/wA/cH/fwUfb7P8A5+4P+/gqP+xPD3/QreH/APwWQ/8AxNU72Dwjp277 V4c8Px7beW5P/EpjOI49u9uF7bl46nPFAGh9vs/+fuD/AL+Cj7fZ/wDP3B/38FZkVv4de/hspfBe j2800LzKJNMtiNqeXu5XPOZQPqrdsE3/AOxPD3/QreH/APwWQ/8AxNAEn2+z/wCfuD/v4KPt9n/z 9wf9/BUf9ieHv+hW8P8A/gsh/wDiaP7E8Pf9Ct4f/wDBZD/8TQBJ9vs/+fuD/v4KPt9n/wA/cH/f wVH/AGJ4e/6Fbw//AOCyH/4mj+xPD3/QreH/APwWQ/8AxNAEn2+z/wCfuD/v4KPt9n/z9wf9/BUf 9ieHv+hW8P8A/gsh/wDiaytL0TQpvE/iLzPDuiMlvbWIiiOnQ7E3GfcQNvU4GT1OB6CgDZ+32f8A z9wf9/BR9vs/+fuD/v4KpJY+GZNTnsB4U0LzYYY5mJ0uHaVcuBjjr+7bP1FWf7E8Pf8AQreH/wDw WQ//ABNAEn2+z/5+4P8Av4KPt9n/AM/cH/fwVH/Ynh7/AKFbw/8A+CyH/wCJrNgHhW8khWy8J6Jc iS3iudyaXAoWORsIx3AHkB2wMkBD3KggGt9vs/8An7g/7+Cj7fZ/8/cH/fwVS06x8M6lplpfw+FN CWK5hSZA+lwhgrAEZwOvNWf7E8Pf9Ct4f/8ABZD/APE0ASfb7P8A5+4P+/go+32f/P3B/wB/BUf9 ieHv+hW8P/8Agsh/+Jo/sTw9/wBCt4f/APBZD/8AE0ASfb7P/n7g/wC/go+32f8Az9wf9/BUf9ie Hv8AoVvD/wD4LIf/AImj+xPD3/QreH//AAWQ/wDxNAEn2+z/AOfuD/v4KPt9n/z9wf8AfwVH/Ynh 7/oVvD//AILIf/iaP7E8Pf8AQreH/wDwWQ//ABNAEn2+z/5+4P8Av4KPt9n/AM/cH/fwVH/Ynh7/ AKFbw/8A+CyH/wCJo/sTw9/0K3h//wAFkP8A8TQBJ9vs/wDn7g/7+Cj7fZ/8/cH/AH8FR/2J4e/6 Fbw//wCCyH/4mj+xPD3/AEK3h/8A8FkP/wATQBJ9vs/+fuD/AL+Cj7fZ/wDP3B/38FR/2J4e/wCh W8P/APgsh/8AiaP7E8Pf9Ct4f/8ABZD/APE0ASfb7P8A5+4P+/go+32f/P3B/wB/BUf9ieHv+hW8 P/8Agsh/+Jo/sTw9/wBCt4f/APBZD/8AE0ASfb7P/n7g/wC/go+32f8Az9wf9/BUf9ieHv8AoVvD /wD4LIf/AImj+xPD3/QreH//AAWQ/wDxNAEn2+z/AOfuD/v4KPt9n/z9wf8AfwVH/Ynh7/oVvD// AILIf/iaP7E8Pf8AQreH/wDwWQ//ABNAEn2+z/5+4P8Av4KPt9n/AM/cH/fwVH/Ynh7/AKFbw/8A +CyH/wCJo/sTw9/0K3h//wAFkP8A8TQBJ9vs/wDn7g/7+Cj7fZ/8/cH/AH8FR/2J4e/6Fbw//wCC yH/4mj+xPD3/AEK3h/8A8FkP/wATQBJ9vs/+fuD/AL+Cj7fZ/wDP3B/38FR/2J4e/wChW8P/APgs h/8AiaP7E8Pf9Ct4f/8ABZD/APE0ASfb7P8A5+4P+/go+32f/P3B/wB/BUf9ieHv+hW8P/8Agsh/ +Jo/sTw9/wBCt4f/APBZD/8AE0ASfb7P/n7g/wC/go+32f8Az9wf9/BUf9ieHv8AoVvD/wD4LIf/ AImj+xPD3/QreH//AAWQ/wDxNAEn2+z/AOfuD/v4KPt9n/z9wf8AfwVH/Ynh7/oVvD//AILIf/ia P7E8Pf8AQreH/wDwWQ//ABNAEn2+z/5+4P8Av4KPt9n/AM/cH/fwVz3jTStEt/Besy23h3RIJltH 2yxadCrocdQdvB9xyK6W+8O+G7e+miTwtoG1WwM6ZD/8TQBH9vs/+fuD/v4KPt9n/wA/cH/fwVH/ AGJ4e/6Fbw//AOCyH/4mj+xPD3/QreH/APwWQ/8AxNAEn2+z/wCfuD/v4KPt9n/z9wf9/BUf9ieH v+hW8P8A/gsh/wDiaP7E8Pf9Ct4f/wDBZD/8TQBJ9vs/+fuD/v4KPt9n/wA/cH/fwVH/AGJ4e/6F bw//AOCyH/4mj+xPD3/QreH/APwWQ/8AxNAEn2+z/wCfuD/v4KPt9n/z9wf9/BUf9ieHv+hW8P8A /gsh/wDiaP7E8Pf9Ct4f/wDBZD/8TQBJ9vs/+fuD/v4KPt9n/wA/cH/fwVH/AGJ4e/6Fbw//AOCy H/4mj+xPD3/QreH/APwWQ/8AxNAFqORJo/MidXTJXcpyMjGRn8R+ddF4Y/5ev+Af1rIaC3ttGsor S1t7WBXl2w28QjReQThRwOcn6mtfwx/y9f8AAP60AdBRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABR RRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFF FABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUU AFFFFAHj/jn/AJEbWv8Ar0f+VbvjGyk1K01qwhZFluYJYULkhQzIQM47c1heOf8AkRta/wCvR/5V 2Unwz8LSyNJJbag7uSzM2rXZJJ6knzaAOD1Ox1DxF9qxp8thnS7uzX7W8Z3vN5e0jy2fgeWc5x1G AecQy6ZqGp+J4NVutJ8q1hktWWGaSN5DsFypYgEqCrTI/DH5RkHd8o9A/wCFX+E/+fS+/wDBrd// AB2j/hV/hP8A59L7/wAGt3/8doA8n0LRp7jw/pFzp+j/AGJIrO2lnH7pDfussEoYbWOTtjkAMm3B kHTLEWdQ8P6rqM2r3sulIJbmG8jtojKjPG0ttAiMTnAP7p0OCcFuMrlq9P8A+FX+E/8An0vv/Brd /wDx2j/hV/hP/n0vv/Brd/8Ax2gDzPUvDGoSalf/AGO38mzbcEEJjG6LFiDGqn5fmWCZQrDbxhvl NPTw7cxaZbxR6ZcSKt00kUNxPCvkZCjJSIKkQyHYPES6EhgG3ulek/8ACr/Cf/Ppff8Ag1u//jtH /Cr/AAn/AM+l9/4Nbv8A+O0AZ9FaH/Cr/Cf/AD6X3/g1u/8A47R/wq/wn/z6X3/g1u//AI7QBn0V of8ACr/Cf/Ppff8Ag1u//jtH/Cr/AAn/AM+l9/4Nbv8A+O0AZ9Zej/8AIy+Kv+vfT/53FdJ/wq/w n/z6X3/g1u//AI7QPhf4TXfttL4b9u/Gq3fzbc7c/vecbmx6bj60AcRrejXeoahelInMMy6coZJd jYiuneTBBBBCMDkYPpzWPdaRDa+Ko7abw8l/Ybbp7OzjSApGm2zBZVdlVRv8zgc5YnHJNen/APCr /Cf/AD6X3/g1u/8A47R/wq/wn/z6X3/g1u//AI7QB5zBo+uWtmthLb/bJZbywup7zzxtxELdZPvf Mz5hZuQAVOc7vlMNj4VurS3tkGnRJLb2+m2+9dgyYbtpJ2U5zhgFk5wWyMjcCB6Z/wAKv8J/8+l9 /wCDW7/+O0f8Kv8ACf8Az6X3/g1u/wD47QB5bpPhbUbe60yS7hu/PhjtAksb2+y3SOKNXjLlTKMs snyx/I2/BI3MR0nhrT5rD7aJbH7KHkBBMocyHksxwcPyeJGCyOMbxlQzdd/wq/wn/wA+l9/4Nbv/ AOO0f8Kv8J/8+l9/4Nbv/wCO0AZ9FaH/AAq/wn/z6X3/AINbv/47R/wq/wAJ/wDPpff+DW7/APjt AGfRWh/wq/wn/wA+l9/4Nbv/AOO0f8Kv8J/8+l9/4Nbv/wCO0AZ9FaH/AAq/wn/z6X3/AINbv/47 R/wq/wAJ/wDPpff+DW7/APjtAGfRWh/wq/wn/wA+l9/4Nbv/AOO0f8Kv8J/8+l9/4Nbv/wCO0AZ9 FaH/AAq/wn/z6X3/AINbv/47R/wq/wAJ/wDPpff+DW7/APjtAGfRWh/wq/wn/wA+l9/4Nbv/AOO0 f8Kv8J/8+l9/4Nbv/wCO0AZ9FaH/AAq/wn/z6X3/AINbv/47R/wq/wAJ/wDPpff+DW7/APjtAGfR Wh/wq/wn/wA+l9/4Nbv/AOO0f8Kv8J/8+l9/4Nbv/wCO0AZ9FaH/AAq/wn/z6X3/AINbv/47R/wq /wAJ/wDPpff+DW7/APjtAGfRWh/wq/wn/wA+l9/4Nbv/AOO0f8Kv8J/8+l9/4Nbv/wCO0AZ9FaH/ AAq/wn/z6X3/AINbv/47R/wq/wAJ/wDPpff+DW7/APjtAGfRWh/wq/wn/wA+l9/4Nbv/AOO0f8Kv 8J/8+l9/4Nbv/wCO0AZ9FaH/AAq/wn/z6X3/AINbv/47R/wq/wAJ/wDPpff+DW7/APjtAGfRWh/w q/wn/wA+l9/4Nbv/AOO0f8Kv8J/8+l9/4Nbv/wCO0AZ9FaH/AAq/wn/z6X3/AINbv/47R/wq/wAJ /wDPpff+DW7/APjtAHH+Of8AkRta/wCvR/5V1mq/8hS4/wB+nSfCzwhLG0cljeOjgqytql0QQeoI 8ypJPhn4WlkaSS21B3clmZtWuyST1JPm0AZtFaH/AAq/wn/z6X3/AINbv/47R/wq/wAJ/wDPpff+ DW7/APjtAGfRWh/wq/wn/wA+l9/4Nbv/AOO0f8Kv8J/8+l9/4Nbv/wCO0AZ9FaH/AAq/wn/z6X3/ AINbv/47R/wq/wAJ/wDPpff+DW7/APjtAGfRWh/wq/wn/wA+l9/4Nbv/AOO0f8Kv8J/8+l9/4Nbv /wCO0AZ9FaH/AAq/wn/z6X3/AINbv/47R/wq/wAJ/wDPpff+DW7/APjtAEc//ILs/wDfk/8AZa1P DH/L1/wD+tZ99pdpo1ja6fYpIltE8mxZJXlYZ2scs5LHknqa0PDH/L1/wD+tAHQUUUUAFFFFABRR RQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFF ABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUA FFFFABRRRQAUUUUAFFFFABRRRQB4/wCOf+RG1r/r0f8AlXsFeP8Ajn/kRta/69H/AJV7BQAUUUUA FFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAU UUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRR RQBzfiL78X++3/oKVJ4Y/wCXr/gH9aj8Rffi/wB9v/QUqTwx/wAvX/AP60AdBRRRQAUUUUAFFFFA BRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAF FFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUU UUAFFFFABRRRQAUUUUAFFFFAHj/jn/kRta/69H/lXsFeP+Of+RG1r/r0f+VewUAFFFFABRRRQAUU UUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRR QAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAc34i+ /F/vt/6ClSeGP+Xr/gH9aj8Rffi/32/9BSpPDH/L1/wD+tAHQUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQB4/45/5EbWv+vR/5V7BXj/jn/kRta/69H/lXsFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAHN+Ivvxf77f8AoKVJ 4Y/5ev8AgH9aj8Rffi/32/8AQUqTwx/y9f8AAP60AdBRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABR RRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFF FABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUU AFFFFAHj/jn/AJEbWv8Ar0f+VewV4/45/wCRG1r/AK9H/lXsFABRRRQAUUUUAFFFFABRRRQAUUUU AFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQA UUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAHN+Ivvxf77f+gpUnhj /l6/4B/Wo/EX34v99v8A0FKk8Mf8vX/AP60AdBRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAU UUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRR RQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFF AHj/AI5/5EbWv+vR/wCVewV4/wCOf+RG1r/r0f8AlXsFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFF ABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUA FFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAHN+Ivvxf77f+gpUnhj/AJev +Af1qPxF9+L/AH2/9BSpPDH/AC9f8A/rQB0FFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRR QAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFA BRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAe P+Of+RG1r/r0f+VewV4/45/5EbWv+vR/5V7BQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAF FFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUU UUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQBzfiL78X++3/oKVJ4Y/5ev+Af1qPxF9 +L/fb/0FKk8Mf8vX/AP60AdBRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAHmOtaV/bmjXel m5W2F1GYjMylggPU4HX6fqOtd1/btp/z1j/8f/8Aia5OigDrP7dtP+esf/j/AP8AE0f27af89Y// AB//AOJrk6KAOs/t20/56x/+P/8AxNH9u2n/AD1j/wDH/wD4muTooA6z+3bT/nrH/wCP/wDxNH9u 2n/PWP8A8f8A/ia5OigDrP7dtP8AnrH/AOP/APxNH9u2n/PWP/x//wCJrk6KAOs/t20/56x/+P8A /wATR/btp/z1j/8AH/8A4muTooA6z+3bT/nrH/4//wDE0f27af8APWP/AMf/APia5OigDrP7dtP+ esf/AI//APE0f27af89Y/wDx/wD+Jrk6KAOs/t20/wCesf8A4/8A/E0f27af89Y//H//AImuTooA 6z+3bT/nrH/4/wD/ABNH9u2n/PWP/wAf/wDia5OigDrP7dtP+esf/j//AMTR/btp/wA9Y/8Ax/8A +Jrk6KAOs/t20/56x/8Aj/8A8TR/btp/z1j/APH/AP4muTooA6z+3bT/AJ6x/wDj/wD8TR/btp/z 1j/8f/8Aia5OigDrP7dtP+esf/j/AP8AE0f27af89Y//AB//AOJrk6KAOs/t20/56x/+P/8AxNH9 u2n/AD1j/wDH/wD4muTooA6z+3bT/nrH/wCP/wDxNH9u2n/PWP8A8f8A/ia5OigDrP7dtP8AnrH/ AOP/APxNH9u2n/PWP/x//wCJrk6KAOs/t20/56x/+P8A/wATR/btp/z1j/8AH/8A4muTooA6z+3b T/nrH/4//wDE0f27af8APWP/AMf/APia5OigDrP7dtP+esf/AI//APE0f27af89Y/wDx/wD+Jrk6 KAOs/t20/wCesf8A4/8A/E0f27af89Y//H//AImuTooA6z+3bT/nrH/4/wD/ABNH9u2n/PWP/wAf /wDia5OigDrP7dtP+esf/j//AMTR/btp/wA9Y/8Ax/8A+Jrk6KAOs/t20/56x/8Aj/8A8TR/btp/ z1j/APH/AP4muTooA6z+3bT/AJ6x/wDj/wD8TR/btp/z1j/8f/8Aia5OigDrP7dtP+esf/j/AP8A E0f27af89Y//AB//AOJrk6KAOs/t20/56x/+P/8AxNH9u2n/AD1j/wDH/wD4muTooA6z+3bT/nrH /wCP/wDxNH9u2n/PWP8A8f8A/ia5OigDrP7dtP8AnrH/AOP/APxNH9u2n/PWP/x//wCJrk6KAOs/ t20/56x/+P8A/wATR/btp/z1j/8AH/8A4muTooA6z+3bT/nrH/4//wDE0f27af8APWP/AMf/APia 5OigDV1m8huzEYpAxDMSADxwo7gehq34Y/5ev+Af1rn66Dwx/wAvX/AP60AdBRRRQAUUUUAFFFFA BRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAF FFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUU UUAFFFFABRRRQAUUUUAFFFFAHH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj6/412FFAHH/2JqP/AD7/ APj6/wCNH9iaj/z7/wDj6/412FFAHH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj6/412FFAHH/2JqP/ AD7/APj6/wCNH9iaj/z7/wDj6/412FFAHH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj6/412FFAHH/2 JqP/AD7/APj6/wCNH9iaj/z7/wDj6/412FFAHH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj6/412FFA HH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj6/412FFAHH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj6/41 2FFAHH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj6/412FFAHH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj 6/412FFAHH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj6/412FFAHH/2JqP/AD7/APj6/wCNH9iaj/z7 /wDj6/412FFAHH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj6/412FFAHH/2JqP/AD7/APj6/wCNH9ia j/z7/wDj6/412FFAHH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj6/412FFAHH/2JqP/AD7/APj6/wCN H9iaj/z7/wDj6/412FFAHH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj6/412FFAHH/2JqP/AD7/APj6 /wCNH9iaj/z7/wDj6/412FFAHH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj6/412FFAHH/2JqP/AD7/ APj6/wCNH9iaj/z7/wDj6/412FFAHH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj6/412FFAHH/2JqP/ AD7/APj6/wCNH9iaj/z7/wDj6/412FFAHH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj6/412FFAHH/2 JqP/AD7/APj6/wCNH9iaj/z7/wDj6/412FFAHH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj6/412FFA HH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj6/412FFAHH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj6/41 2FFAHH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj6/412FFAHH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj 6/412FFAHH/2JqP/AD7/APj6/wCNH9iaj/z7/wDj6/412FFAHH/2JqP/AD7/APj6/wCNbGhWNxZ/ aPtEezft2/MDnGfT61sUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFF FFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUU UAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB RRRQB//Z ------=_NextPart_000_0051_01C14CF1.ECC13980-- From dyoo@hkn.eecs.berkeley.edu Thu Oct 4 20:36:11 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 4 Oct 2001 12:36:11 -0700 (PDT) Subject: [Tutor] Stuck with classes In-Reply-To: <3BBCA597.67C6EEC8@venix.com> Message-ID: On Thu, 4 Oct 2001, Lloyd Kvam wrote: > I don't follow what you are doing but.... > gg.addGen(p) > AND within the addGen method > yyy.AddWindow(p.GridSizer, ...) This approach will work. However, it hardcodes genGrid.addGen to always use that particular matrixPanel, and that might limit the usefulness of the genGrid class. It might be ok if this is a one-shot thing, but it's usually better to make classes stand alone without depending on global variables. If we have two genGrids, for example, these two might not necessarily want to share the same matrixPanel... maybe they're jealous! *grin* To avoid potential catfights, we can use a similar solution: we can pass off a matrixPanel to the genGrid as soon as the genGrid is created: ### class genGrid: def __init__(self, matrixPanel): self.matrixPanel = matrixPanel def addGen(self, panel): # Create Function table self.DescWin = wxGrid(...) [...] yyy.AddWindow(self.matrixPanel.GridSizer) p = matrixPanel(frame1, -1) gr = p.makeGrid() gg = genGrid(p) ### Here, we can say that every genGrid remembers which matrixPanel it is associated with. That is, a genGrid always "has a" matrixPanel, since it's now part of the constructor: every genGrid that springs into existence will have a matrixPanel in it. And also a good reason to involve it in the constructor: if a genGrid can't function --- can't live --- without its matrixPanel, then that's a sign that we should get genGrid involved, hand in hand, with a matrixPanel from the very beginning. Hope this helps! From danny.kohn@systematik.se Thu Oct 4 21:09:03 2001 From: danny.kohn@systematik.se (Danny Kohn) Date: Thu, 4 Oct 2001 22:09:03 +0200 Subject: SV: [Tutor] Stuck with classes In-Reply-To: Message-ID: Find oop somewhat complicated I must say. Obviously I can go back to = functions but I at least I want to understand it proper so that my = choice will not be one of ignorance. Danny Yoo is correct in that I want to be able to have many concurrent = instances of a matrixPanel. Thanks for all the comments. Will study them carefully. /Danny Kohn | -----Ursprungligt meddelande----- | Fran: tutor-admin@python.org [mailto:tutor-admin@python.org]For Danny | Yoo | Skickat: den 4 oktober 2001 21:36 | Till: Lloyd Kvam | Kopia: Danny Kohn; Python Tutor mailing list | Amne: Re: [Tutor] Stuck with classes |=20 |=20 | On Thu, 4 Oct 2001, Lloyd Kvam wrote: |=20 | > I don't follow what you are doing but.... | > gg.addGen(p) | > AND within the addGen method | > yyy.AddWindow(p.GridSizer, ...) |=20 | This approach will work. However, it hardcodes genGrid.addGen to = always | use that particular matrixPanel, and that might limit the usefulness = of | the genGrid class. It might be ok if this is a one-shot thing, but = it's | usually better to make classes stand alone without depending on global | variables. |=20 | If we have two genGrids, for example, these two might not necessarily = want | to share the same matrixPanel... maybe they're jealous! *grin* |=20 |=20 | To avoid potential catfights, we can use a similar solution: we can = pass | off a matrixPanel to the genGrid as soon as the genGrid is created: |=20 | ### | class genGrid: | def __init__(self, matrixPanel): | self.matrixPanel =3D matrixPanel |=20 | def addGen(self, panel): | # Create Function table | self.DescWin =3D wxGrid(...) | [...] | yyy.AddWindow(self.matrixPanel.GridSizer) |=20 | p =3D matrixPanel(frame1, -1) | gr =3D p.makeGrid() | gg =3D genGrid(p) | ### |=20 | Here, we can say that every genGrid remembers which matrixPanel it is | associated with. That is, a genGrid always "has a" matrixPanel, since | it's now part of the constructor: every genGrid that springs into | existence will have a matrixPanel in it. |=20 |=20 | And also a good reason to involve it in the constructor: if a genGrid | can't function --- can't live --- without its matrixPanel, then that's = a | sign that we should get genGrid involved, hand in hand, with a = matrixPanel | from the very beginning. |=20 |=20 | Hope this helps! |=20 |=20 | _______________________________________________ | Tutor maillist - Tutor@python.org | http://mail.python.org/mailman/listinfo/tutor |=20 From jerryl@europa.com Thu Oct 4 21:33:14 2001 From: jerryl@europa.com (Jerry Lake) Date: Thu, 4 Oct 2001 13:33:14 -0700 Subject: [Tutor] sendmail In-Reply-To: Message-ID: <000001c14d13$cc26d960$0103670a@europa.com> does anyone have a quick script I can use to see if my sendmail is working ? Thanks, Jerry Lake Interface Engineering Technician From shalehperry@home.com Thu Oct 4 21:44:00 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Thu, 04 Oct 2001 13:44:00 -0700 (PDT) Subject: SV: [Tutor] Stuck with classes In-Reply-To: Message-ID: On 04-Oct-2001 Danny Kohn wrote: > Find oop somewhat complicated I must say. Obviously I can go back to > functions but I at least I want to understand it proper so that my choice > will not be one of ignorance. > > Danny Yoo is correct in that I want to be able to have many concurrent > instances of a matrixPanel. > OOP is about thinking in terms of things interactring with each other. Imperative programming (C, etc) uses tools (functions) to act on the participants without their control. in classic imperative/C style you would have: setupParent(parent, child1, child2) whereas in OOP you have: parent.setup(child1, child2) This is what you have to wrap your head around. OOP is all about metaphor and using the real world to help the abstract make sense. Look at your example. There is this thing called a "panel" which has certain properties and things it knows how to do like draw itself. By adding other objects the panel can do other things. So when it draws itself it then tells other attached objects to also draw themself. Understanding a group of classes is really about understanding how they interact with each other. From ignacio@openservices.net Thu Oct 4 21:52:54 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Thu, 4 Oct 2001 16:52:54 -0400 (EDT) Subject: [Tutor] sendmail In-Reply-To: <000001c14d13$cc26d960$0103670a@europa.com> Message-ID: On Thu, 4 Oct 2001, Jerry Lake wrote: > does anyone have a quick script > I can use to see if my sendmail > is working ? import smtplib cxn=smtplib.SMTP('localhost') cxn.quit() -- Ignacio Vazquez-Abrams From jerryl@europa.com Thu Oct 4 22:16:05 2001 From: jerryl@europa.com (Jerry Lake) Date: Thu, 4 Oct 2001 14:16:05 -0700 Subject: [Tutor] logic ? In-Reply-To: Message-ID: <000101c14d19$c7b60300$0103670a@europa.com> for some reason, I can't get this to function properly, if someone can point me in the right direction, I'd appreciate it. the problem comes in at the if/else in the slope formula, it returns all slopes as 0. #!/usr/bin/python2 import math x1 = input("Enter a coordinate for x1: ") y1 = input("Enter a coordinate for y1: ") x2 = input("Enter a coordinate for x2: ") y2 = input("Enter a coordinate for y2: ") def distance(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 dsquared = dx**2 + dy**2 result = math.sqrt(dsquared) return result def slope(x1, y1, x2, y2): x = x1 - x2 y = y1 - y2 if (x or y == 0): slope = 0 else: slope = x / y return slope print "The distance between the points is", distance(x1, y1, x2, y2) print "The slope of the two points is ", slope(x1, y1, x2, y2) Regards, Jerry Lake - jlake@US.NET Interface Engineering Technician -----Original Message----- From: Ignacio Vazquez-Abrams [mailto:ignacio@openservices.net] Sent: Thursday, October 04, 2001 1:53 PM To: Python Tutor mailing list Subject: Re: [Tutor] sendmail On Thu, 4 Oct 2001, Jerry Lake wrote: > does anyone have a quick script > I can use to see if my sendmail > is working ? import smtplib cxn=smtplib.SMTP('localhost') cxn.quit() -- Ignacio Vazquez-Abrams _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From ignacio@openservices.net Thu Oct 4 22:30:48 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Thu, 4 Oct 2001 17:30:48 -0400 (EDT) Subject: [Tutor] logic ? In-Reply-To: <000101c14d19$c7b60300$0103670a@europa.com> Message-ID: On Thu, 4 Oct 2001, Jerry Lake wrote: > for some reason, I can't get this to function > properly, if someone can point me in the right > direction, I'd appreciate it. the problem comes > in at the if/else in the slope formula, it returns > all slopes as 0. > > > #!/usr/bin/python2 > > import math > > x1 = input("Enter a coordinate for x1: ") > y1 = input("Enter a coordinate for y1: ") > x2 = input("Enter a coordinate for x2: ") > y2 = input("Enter a coordinate for y2: ") > > def distance(x1, y1, x2, y2): > dx = x2 - x1 > dy = y2 - y1 > dsquared = dx**2 + dy**2 > result = math.sqrt(dsquared) > return result > > def slope(x1, y1, x2, y2): > x = x1 - x2 > y = y1 - y2 > if (x or y == 0): > slope = 0 > else: > slope = x / y > return slope > > print "The distance between the points is", distance(x1, y1, x2, y2) > print "The slope of the two points is ", slope(x1, y1, x2, y2) > > There are three problems: 1) input() evaluates the inputted text, leading to a security hole. Use raw_input() instead and convert the input to a float. 2) Your condition in the if statement is wrong. it should read "x==0 or y==0", although "y==0", or even just "y" will do for this exercise. 3) By default, the "/" operator does integer division if both operands are integers. You need to use float() to convert them to floats. -- Ignacio Vazquez-Abrams From dyoo@hkn.eecs.berkeley.edu Thu Oct 4 22:34:05 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 4 Oct 2001 14:34:05 -0700 (PDT) Subject: [Tutor] logic ? In-Reply-To: <000101c14d19$c7b60300$0103670a@europa.com> Message-ID: On Thu, 4 Oct 2001, Jerry Lake wrote: > for some reason, I can't get this to function > properly, if someone can point me in the right > direction, I'd appreciate it. the problem comes > in at the if/else in the slope formula, it returns > all slopes as 0. > > def slope(x1, y1, x2, y2): > x = x1 - x2 > y = y1 - y2 > if (x or y == 0): ^^^^^^^^^^^^^ We as humans understand what you mean. However, Python's seeing this in a different light: if x or (y == 0): That is, as long as x is a "true" value, the condition holds: ### >>> 1 or 1 == 0 1 ### To fix this, you can write the logic like this: ### if x == 0 or y == 0: ### But I really like this way: ### if 0 in (x, y): ### which is neat since it reverses the "normal" role that we often see with the 'in' operator. Usually, we have the variable to the left of 'in', but we don't have to be constrained to this. Hope this helps! From ignacio@openservices.net Thu Oct 4 22:37:20 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Thu, 4 Oct 2001 17:37:20 -0400 (EDT) Subject: [Tutor] logic ? In-Reply-To: Message-ID: On Thu, 4 Oct 2001, Ignacio Vazquez-Abrams wrote: > 2) Your condition in the if statement is wrong. it should read "x==0 or y==0", > although "y==0", or even just "y" will do for this exercise. I meant "not y" for that last one, of course. -- Ignacio Vazquez-Abrams From shalehperry@home.com Thu Oct 4 22:38:34 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Thu, 04 Oct 2001 14:38:34 -0700 (PDT) Subject: [Tutor] logic ? In-Reply-To: Message-ID: > > 2) Your condition in the if statement is wrong. it should read "x==0 or > y==0", > although "y==0", or even just "y" will do for this exercise. > to further clarify this, python sees "if (x or y == 0)" as "if (x) or (y == 0)". From jerryl@europa.com Thu Oct 4 22:47:23 2001 From: jerryl@europa.com (Jerry Lake) Date: Thu, 4 Oct 2001 14:47:23 -0700 Subject: [Tutor] logic ? In-Reply-To: Message-ID: <000201c14d1e$273002a0$0103670a@europa.com> thank you all for the quick help. additionally I'm having issues converting the raw input to float what I have is as follows [upstart@localhost learn]$ ./function4.py Enter a coordinate for x1: 1 Enter a coordinate for y1: 3 Enter a coordinate for x2: 6 Enter a coordinate for y2: 5 The distance between the points is Traceback (most recent call last): File "./function4.py", line 37, in ? print "The distance between the points is", distance(x1, y1, x2, y2) File "./function4.py", line 20, in distance dx = x2 - x1 TypeError: unsupported operand type(s) for - # import the math module import math # get coordinates from user input x1 = raw_input("Enter a coordinate for x1: ") y1 = raw_input("Enter a coordinate for y1: ") x2 = raw_input("Enter a coordinate for x2: ") y2 = raw_input("Enter a coordinate for y2: ") # convert raw input to floating point numbers float(x1) float(x2) float(y1) float(y2) # create function to determine distance between coordinates def distance(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 dsquared = dx**2 + dy**2 result = math.sqrt(dsquared) return result # create function to determine slope of coordinates def slope(x1, y1, x2, y2): x = x1 - x2 y = y1 - y2 if (x == 0 or y == 0): slope = 0 else: slope = x / y return slope # print distance and slope of coordinates to screen print "The distance between the points is", distance(x1, y1, x2, y2) print "The slope of the two points is ", slope(x1, y1, x2, y2) Jerry Lake - jlake@US.NET Interface Engineering Technician Jerry Lake - jlake@US.NET Interface Engineering Technician -----Original Message----- From: Sean 'Shaleh' Perry [mailto:shalehperry@home.com] Sent: Thursday, October 04, 2001 2:39 PM To: Python Tutor mailing list Subject: Re: [Tutor] logic ? > > 2) Your condition in the if statement is wrong. it should read "x==0 or > y==0", > although "y==0", or even just "y" will do for this exercise. > to further clarify this, python sees "if (x or y == 0)" as "if (x) or (y == 0)". _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From ignacio@openservices.net Thu Oct 4 22:57:06 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Thu, 4 Oct 2001 17:57:06 -0400 (EDT) Subject: [Tutor] logic ? In-Reply-To: <000201c14d1e$273002a0$0103670a@europa.com> Message-ID: On Thu, 4 Oct 2001, Jerry Lake wrote: > thank you all for the quick help. > > additionally I'm having issues > converting the raw input to float > what I have is as follows > > [snip] > > float(x1) > float(x2) > float(y1) > float(y2) Whoops. float() returns the value as a float, so you have to say "x1=float(x1)", etc. -- Ignacio Vazquez-Abrams From dyoo@hkn.eecs.berkeley.edu Thu Oct 4 22:57:57 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 4 Oct 2001 14:57:57 -0700 (PDT) Subject: [Tutor] Creating windows shortcuts with win32com.shell In-Reply-To: Message-ID: On Wed, 3 Oct 2001, Reed, David wrote: > I'm a looking for a module and method that will allow me to make > Windows 2000 shortcut files or (lnk). Do you have documentation or > reference as to how to do this? You might want to ask your question on the comp.lang.python newsgroup too --- this might be too specialized a question, and I'm not sure if many of us here are familiar with Win2k-specific stuff. There's a web site that has reference documentation for Windows stuff: http://aspn.activestate.com/ASPN/Reference/Products/ActivePython/PythonWin32Extensions/PythonWin32Extensions.html but it looks really dense... searching... ah! It looks like you'll want the IShellLink interface. The win32all "Windows Extensions" page mentions that you can make shortcuts with it: """IShellLink interface now supported in the "win32com.shell" extension, which allows Python to create and/or resolve Windows "shortcut" files.""" http://starship.python.net/crew/mhammond/win32/RecentChangeHistory.html Take a look at: http://aspn.activestate.com//ASPN/Reference/Products/ActivePython/win32com/win32com.shell_and_Windows_Shell_Links.html and http://aspn.activestate.com//ASPN/Reference/Products/ActivePython/win32com/PyIShellLink.html which talks about PyIShellLink objects: they appear to be what you're looking for. From jerryl@europa.com Thu Oct 4 23:01:27 2001 From: jerryl@europa.com (Jerry Lake) Date: Thu, 4 Oct 2001 15:01:27 -0700 Subject: [Tutor] logic ? In-Reply-To: Message-ID: <000301c14d20$1e3eaa00$0103670a@europa.com> oops, thanks I think I get it now Regards, Jerry Lake Interface Engineering Technician Jerry Lake - jlake@US.NET Interface Engineering Technician -----Original Message----- From: Ignacio Vazquez-Abrams [mailto:ignacio@openservices.net] Sent: Thursday, October 04, 2001 2:57 PM To: Python Tutor mailing list Subject: RE: [Tutor] logic ? On Thu, 4 Oct 2001, Jerry Lake wrote: > thank you all for the quick help. > > additionally I'm having issues > converting the raw input to float > what I have is as follows > > [snip] > > float(x1) > float(x2) > float(y1) > float(y2) Whoops. float() returns the value as a float, so you have to say "x1=float(x1)", etc. -- Ignacio Vazquez-Abrams _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dyoo@hkn.eecs.berkeley.edu Thu Oct 4 23:05:42 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 4 Oct 2001 15:05:42 -0700 (PDT) Subject: [Tutor] logic ? In-Reply-To: <000201c14d1e$273002a0$0103670a@europa.com> Message-ID: On Thu, 4 Oct 2001, Jerry Lake wrote: > thank you all for the quick help. > > additionally I'm having issues > converting the raw input to float > what I have is as follows > > # convert raw input to floating point numbers > float(x1) > float(x2) > float(y1) > float(y2) You probably mean: x1 = float(x1) x2 = float(x2) ... Python's conversion functions don't touch the original values, but they do give back or "return" values that we can use. We can capture those values by reassigning x1. Python strings are "immutable" --- their contents can't be altered directly. ### >>> mystring = "Molecular Biology of the Cell" >>> mystring[-4] = "B" Traceback (most recent call last): File "", line 1, in ? TypeError: object doesn't support item assignment ### This stands in direct contrast with the primitive strings that some other programming languages provide (although Java does share the same idea of immutability.) You'll get it working eventually... *grin* Good luck! From lumbricus@gmx.net Fri Oct 5 00:13:45 2001 From: lumbricus@gmx.net (Joerg Woelke) Date: Fri, 5 Oct 2001 01:13:45 +0200 Subject: [Tutor] sendmail In-Reply-To: ; from ignacio@openservices.net on Thu, Oct 04, 2001 at 04:52:54PM -0400 References: <000001c14d13$cc26d960$0103670a@europa.com> Message-ID: <20011005011345.A12420@Laplace.localdomain> On Thu, Oct 04, 2001 at 04:52:54PM -0400, Ignacio Vazquez-Abrams wrote: > On Thu, 4 Oct 2001, Jerry Lake wrote: > > > does anyone have a quick script > > I can use to see if my sendmail > > is working ? > > import smtplib > > cxn=smtplib.SMTP('localhost') > cxn.quit() or: import os os.system("telnet localhost 25") SCNR J"o! ;-) -- Distrust all those who love you extremely upon a very slight acquaintance and without any visible reason. -- Lord Chesterfield From pythonpython@hotmail.com Fri Oct 5 04:14:12 2001 From: pythonpython@hotmail.com (Newbie Python) Date: Fri, 05 Oct 2001 03:14:12 +0000 Subject: [Tutor] a re question Message-ID: How can use re to match something like: js=""" """ I use this: re.match(r"",js,re.S) but it will not match.. Can you please tell me why and how to write the regex? Thanks a lot Hy _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp From ignacio@openservices.net Fri Oct 5 04:41:43 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Thu, 4 Oct 2001 23:41:43 -0400 (EDT) Subject: [Tutor] a re question In-Reply-To: Message-ID: On Fri, 5 Oct 2001, Newbie Python wrote: > How can use re to match something like: > js=""" > > """ > > I use this: > re.match(r"",js,re.S) > but it will not match.. > > Can you please tell me why and how to write the regex? There's a newline in the beginning of your string. Use ".*]*>.*.*" instead. -- Ignacio Vazquez-Abrams From pythonpython@hotmail.com Fri Oct 5 05:21:25 2001 From: pythonpython@hotmail.com (Hy Python) Date: Fri, 05 Oct 2001 04:21:25 +0000 Subject: [Tutor] another re question Message-ID: what if it's like this: html=""" blahhhhhhlaaaa blahlbaaalalablaaa dasdfas sdafblala balalala sddsfasdf """ How can I do a re.findall ? I used this: re.findall(r"\n?]+?>.+?",html) it does not work. Why? Thanks a lot.. Hy >From: Ignacio Vazquez-Abrams >To: >Subject: Re: [Tutor] a re question >Date: Thu, 4 Oct 2001 23:41:43 -0400 (EDT) > >On Fri, 5 Oct 2001, Newbie Python wrote: > > > How can use re to match something like: > > js=""" > > > > """ > > > > I use this: > > re.match(r"",js,re.S) > > but it will not match.. > > > > Can you please tell me why and how to write the regex? > >There's a newline in the beginning of your string. Use >".*]*>.*.*" instead. > >-- >Ignacio Vazquez-Abrams > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp From ignacio@openservices.net Fri Oct 5 05:31:30 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Fri, 5 Oct 2001 00:31:30 -0400 (EDT) Subject: [Tutor] another re question In-Reply-To: Message-ID: On Fri, 5 Oct 2001, Hy Python wrote: > what if it's like this: > html=""" > > > blahhhhhhlaaaa > > > blahlbaaalalablaaa > > dasdfas sdafblala > balalala > sddsfasdf > > > > """ > > How can I do a re.findall ? > I used this: > re.findall(r"\n?]+?>.+?",html) > it does not work. Why? Because the dot doesn't match the newline unless you pass re.S or re.DOTALL as a flag, which you cannot do with re.findall(). Use the following instead: --- regex=re.compile(']*>.*', re.S) regex.findall(html) --- -- Ignacio Vazquez-Abrams From dyoo@hkn.eecs.berkeley.edu Fri Oct 5 06:09:38 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 4 Oct 2001 22:09:38 -0700 (PDT) Subject: [Tutor] Help - how to do a window In-Reply-To: Message-ID: On Thu, 4 Oct 2001, Glauco Silva wrote: > I have other doubt . I would like to know if anybody can help me . I > don't know how to do this kind of window attached . If anybody know , > please help me ! Thank you ! In Tkinter, wxPython, or some other GUI system? It looks like the window you're showing is a frame with two list boxes, packed left to right. If we want Tkinter to arrange listboxes in that way, we can do that like this: ### from Tkinter import * root = Tk() frame = Frame(root) frame.pack() listbox1 = Listbox(frame) listbox1.pack(side=LEFT) listbox2 = Listbox(frame) listbox2.pack(side=LEFT) ### (I'm unable to test this code at the moment, so it might have typos. Sorry!) Is this what you're looking for? From jyothi@ncoretech.com Fri Oct 5 06:51:59 2001 From: jyothi@ncoretech.com (jyothi Guruprasanna) Date: Fri, 5 Oct 2001 11:21:59 +0530 Subject: [Tutor] about events Message-ID: Hi, I have done a Gui which looks just like a calculator. For the display part of the calculator, I am using Pmw.ScrolledText. Now I am embedding 3 instances of this calculator on root. The Gui will look like a frame with 3 calculators on this. My problem is when I start typing on one of calculator display and immediately switch to other, whatever I type it will go to the first calculator display only where I was intially typing. it will not come to the recent one. So how to get focus on the display when I move my mouse pointer or click on that calculator display??.. Thanks and Regards, Jyohti. From dyoo@hkn.eecs.berkeley.edu Fri Oct 5 06:31:52 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 4 Oct 2001 22:31:52 -0700 (PDT) Subject: [Tutor] a re question In-Reply-To: Message-ID: On Fri, 5 Oct 2001, Newbie Python wrote: > How can use re to match something like: > js=""" > > """ > > I use this: > re.match(r"",js,re.S) > but it will not match.. > > Can you please tell me why and how to write the regex? Ah. There's a difference between Python's "match()" and "search()" regular expression functions: match() automatically assumes that the matching occurs right at the beginning of our text. Take a look at: http://www.python.org/doc/lib/matching-searching.html for more details about this. Don't worry: everyone who starts off with Python regular expressions gets caught by this at least once. *grin* By the way, you can also use the SGMLParser class that's in the 'sgmllib' module: it knows how to read HTML-like pages, and it's pretty reliable. Using sgmllib does require that you feel a little comfortable about classes, so if you're not familiar with them, hmmm... think of this as a motivating example. *grin* ### import sgmllib class MyJavascriptExtractor(sgmllib.SGMLParser): def __init__(self): sgmllib.SGMLParser.__init__(self) self.in_javascript = 0 self.jscontent = [] def getContent(self): return '\n'.join(self.jscontent) ########################################################## ## Below are handlers that will be called when we feed() a ## document to the parser. def start_script(self, attributes): self.in_javascript = 1 def handle_data(self, data): if self.in_javascript: self.jscontent.append(data) def end_script(self): self.in_javascript = 0 ### Here's an example run: ### >>> mystr = """ ... hello world, this is a test. ... """ >>> extractor = MyJavascriptExtractor() >>> extractor.feed(mystr) >>> extractor.getContent() '\ndocument.print("And this is another!");\nfunction factorial(x) {\n if (x == 0) return 1;\n else return x * factorial(x-1);\n}\n' ### I have no idea if the above is valid Javascript. *grin* From dyoo@hkn.eecs.berkeley.edu Fri Oct 5 06:50:25 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 4 Oct 2001 22:50:25 -0700 (PDT) Subject: [Tutor] another re question [using findall() with flags] In-Reply-To: Message-ID: On Fri, 5 Oct 2001, Ignacio Vazquez-Abrams wrote: > > How can I do a re.findall ? > > I used this: > > re.findall(r"\n?]+?>.+?",html) > > it does not work. Why? > > Because the dot doesn't match the newline unless you pass re.S or > re.DOTALL as a flag, which you cannot do with re.findall(). Use the > following instead: It is possible to embed this DOTALL-ish flag as part of our findall() pattern, if we use the "(?s)" "pattern": ### >>> re.findall(r"(?s)Hello.+?\.", """Hello world. ... Hello, my name is ... Inigo Montoya. ... """) ['Hello world.', 'Hello, my name is\nInigo Montoya.'] ### See: http://www.python.org/doc/lib/re-syntax.html for more details. However, I agree with Ignacio: use re.compile() instead of "(?s)", just to avoid putting yet another mysterious meta-pattern-like thing in that complicated string. Also, do you know about using re.VERBOSE yet? If you're really enamored with regular expressions, you should do as much as you can to make sure you can still read those regexes the day after tomorrow. The re.VERBOSE flag will let you spread a regular expression across several lines, even allowing comments: ### >>> hello_re = re.compile(r""" ... Hello ## Let's begin with a "Hello" ... .+? ## following by some nongreedy ... ## characters, ... \. ## and top it off with a period. ... """, re.S | re.VERBOSE) ## The bitwise or is intentional. >>> hello_re.findall("""Hello world. ... Hello, my ... name is ... Inigo Montoga.""") ['Hello world.', 'Hello, my\nname is\nInigo Montoga.'] ### Good luck to you. From danny.kohn@systematik.se Fri Oct 5 12:15:15 2001 From: danny.kohn@systematik.se (Danny Kohn) Date: Fri, 5 Oct 2001 13:15:15 +0200 Subject: SV: [Tutor] Stuck with classes - events In-Reply-To: Message-ID: Well, thanks to all the help I did solve that so my classes are now = working. But then I come to another issue. Below is my class layout. = ObjGrid and StatGrid are both grids inside a sizer on a MatrixPanel on = MyFrame. Now lets say that I clicked on one cell in one of the two grids and = enter a letter. If I understand things correctly the oop way of doing = this would be to implement event handling in ObjGrid and StatGrid = respecively and process the related event in the related class instance. = I haven't tested it but I think I understand how to do that. But then one of my needs is to be able detect for example Ctrl+Left and = when that combination is pressed go to the other matrix. In "normal" = programming I would probably have done this with some flags. I guess that I should trap the combination in MatrixPanel while let the = processing of the data entered should be traped by ObjGrid and StatGrid = respecively. Have now idea how to do this but I will probably solve that = also. My question is, what is the best way to implement for the MatrixPanel = class to remember and get updated on what the active grid is so that it = could be able to move to the other grid when I click Ctrl+Left? class MyFrame(wxFrame): def __init__(self, parent, id, title, class MatrixPanel(wxPanel): def __init__(self, parent, id): wxPanel.__init__(self, parent, id, wxDefaultPosition, wxPyDefaultSize) def makeGrid(self): class ObjGrid: def __init__(self, parent, gz): def setRow(self, row, type, operand, name): class StatGrid: def __init__(self, parent, gz): def setRow(self, row, type, operand, name): Regards Danny Kohn Tel: +46 (708) 140 300 (\_/) )) ICQ: 1328817 ('.')=3D// Miau! Ham: SMONBJ ( ~~~ )/ Rrrrrui! =20 `w---w? From jyothi@ncoretech.com Fri Oct 5 13:28:50 2001 From: jyothi@ncoretech.com (jyothi Guruprasanna) Date: Fri, 5 Oct 2001 17:58:50 +0530 Subject: [Tutor] Doubt regarding frame... Message-ID: Hi, I am trying to put the the instances of a class which inherits from Frame into root(Tk()). I pack them using the pack option side=LEFT. I am able to place 3 instances into root properly. No problem till here. After this I want to pack a Pmw.ScrolledText object at the bottom of the root . I am using pack option side=BOTTOM. But it is not inserting the Pmw.ScrolledText object at the bottom. instead it is inserting to the side. I want display with 3 instances of the class which inherits from Frame on the top( side by side ) and one Pmw.ScrolledText object at the bottom of them. what should I do for this. side=BOTTOM is not working... Thanks and Regards, Jyothi. From alan.gauld@bt.com Fri Oct 5 13:39:22 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 5 Oct 2001 13:39:22 +0100 Subject: [Tutor] Help - how to do a window Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFBE@mbtlipnt02.btlabs.bt.co.uk> ------_=_NextPart_001_01C14D9A.C2A3C6A0 Content-type: text/plain; charset="ISO-8859-1" I have other doubt . I would like to know if anybody can help me . I don't know how to do this kind of window attached . It looks a lot like a Windows table type widget. There isn't a native widget in Tkinter for this type of display but with some (quite a lot!) effort you can fake it. You have a frame containing a menubar and a second frame. This latter frame contains a row of buttons (Output, input etc) and a large text area. By writing suitable event handlers for the buttons you can sort the contents of the text field etc - assuming thats the intent... Of course you might be able to find a porewritten table object somewhere. Or if you are using a different toolkit (wxPython say) it may well have such a beast. Alan g. ------_=_NextPart_001_01C14D9A.C2A3C6A0 Content-type: text/html; charset="ISO-8859-1"
I have other doubt . I would like to know if anybody can help me . I don't know how to do this kind of window attached . 
It looks a lot like a Windows table type widget.
There isn't a native widget in Tkinter for this type
of display but with some (quite a lot!) effort you
can fake it.
 
You have a frame containing a menubar and a second
frame. This latter frame contains a row of buttons
(Output, input etc) and a large text area. By writing
suitable event handlers for the buttons you can sort
the contents of the text field etc - assuming thats
the intent...
 
Of course you might be able to find a porewritten
table object somewhere.
 
Or if you are using a different toolkit (wxPython say)
it may well have such a beast.
 
Alan g.
------_=_NextPart_001_01C14D9A.C2A3C6A0-- From alan.gauld@bt.com Fri Oct 5 13:47:42 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 5 Oct 2001 13:47:42 +0100 Subject: [Tutor] Stuck with classes Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFBF@mbtlipnt02.btlabs.bt.co.uk> > On Thu, 4 Oct 2001, Danny Kohn wrote: > > class matrixPanel(wxPanel): > > def makeGrid(): > > self.GridSizer = wxFlexGridSizer( 2, 3, 1, 1 ) > > > > class genGrid: > > def addGen(self, panel): > > yyy.AddWindow( ...) > > > > p = matrixPanel(frame1, -1) > > gr = p.makeGrid > > gg=genGrid() > > > > How in earth do I pass self.GridSizer in matrixPanel > > to yyy? Or do I have to do this in a nested class. First, I'd ask why you want to? You are passing an object's internal member data first to an intermediate object which merely passes it through to a third object (possibly an internal attribiute of the second object?). This is usually a bad thing in OO design terms. However it may be necessary, it's hard to tell how your design works from the code snippet. But personally I'd favour passing the entire panel rather than its internal attribute - that way we only need the yyy object to be tightly coupled to the panel internals. The yyy object method can then extract the attribute as and when its needed. But I'd still ask *why* you are passing that around so much - maybe the attribute is in the wrong class to start with? Could yyy be the true master of that object? Depends where else and how you use it... Just some thoughts. Alan G. > and then slightly tweak genGrid.addGen() to take in another > parameter --- not only the panel, but a GridSizer instance: But if it has the panel it has the GridSizer too - we're just increasing the size of the coupling for no benefit. > I have to admit, though, that I'm not familiar enough > with wxPython to know if this is an wxPythonic approach Likewise... > Alternatively, we can pass the whole matrixPanel off to the > genGrid. Yes, that's my preferred route assuming the GenGrid really is an essential part of the panel to start with. Alan g. From Brad.Reisfeld@carrier.utc.com Fri Oct 5 14:45:51 2001 From: Brad.Reisfeld@carrier.utc.com (Reisfeld, Brad CAR) Date: Fri, 5 Oct 2001 09:45:51 -0400 Subject: [Tutor] Treating program exceptions Message-ID: <590E1FF8B6A4D4118CB200508B63D23E020A6CB2@carussyrmb01.carrier.utc.com> Hi, I am wondering about the best way to flag out errors to my program's users or calling programs. Possible as a holdover from my shell programming experience, I currently do something like the following: --- (OKAY, NUM_PARAM_ERR, INVALID_PROP_ERR, DUP_PROP_ERR, INVALID_VAL_ERR, OUT_OF_B\ OUNDS_ERR, EMPTY_FILE_ERR, OUTPUT_ERR) = range(8) arg_list = sys.argv prog_name = os.path.basename(arg_list.pop(0)) if num_args != 6 and num_args != 4: print "Error: Improper number of arguments." print "Usage: %s property1 value1 property2 value2 [property3 value3]" % (p\ rog_name) sys.exit(NUM_PARAM_ERR) --- This way, I can get the error message and exit status from the program. This does not seem particularly 'Pythonic' to me. I suppose I should be using an exception class of some sort and raise these exceptions when they occur. Something perhaps like --- class MyProgError(Exception): pass class ImproperArgs(MyProgError): pass if num_args != 6 and num_args != 4: raise ImproperArgs, "Usage: %s property1 value1 property2 value2 [property3 value3]" % (p\ rog_name) --- Using this approach, is there a way to return an error status code [like sys.exit()] as well as a message? Are there other alternatives I should be considering? Any suggestions are appreciated. -Brad From shalehperry@home.com Fri Oct 5 15:45:49 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Fri, 05 Oct 2001 07:45:49 -0700 (PDT) Subject: SV: [Tutor] Stuck with classes - events In-Reply-To: Message-ID: > > But then one of my needs is to be able detect for example Ctrl+Left and when > that combination is pressed go to the other matrix. In "normal" programming I > would probably have done this with some flags. > > I guess that I should trap the combination in MatrixPanel while let the > processing of the data entered should be traped by ObjGrid and StatGrid > respecively. Have now idea how to do this but I will probably solve that > also. > Consider this. When item A gets a Ctrl+Left click it tells its parent to make it the current object. The parent then makes item A the current object (gives focus, etc). Essentially the object tells its controller "my turn please". parent.givefocus(child) called from within child.handleKeyPress(). From shalehperry@home.com Fri Oct 5 16:02:46 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Fri, 05 Oct 2001 08:02:46 -0700 (PDT) Subject: [Tutor] Treating program exceptions In-Reply-To: <590E1FF8B6A4D4118CB200508B63D23E020A6CB2@carussyrmb01.carrier.utc.com> Message-ID: > --- > class MyProgError(Exception): pass > class ImproperArgs(MyProgError): pass > > if num_args != 6 and num_args != 4: > raise ImproperArgs, "Usage: %s property1 value1 property2 value2 > [property3 value3]" % (p\ > rog_name) > --- > > Using this approach, is there a way to return an error status code [like > sys.exit()] as well as a message? > the item passes along with the exception can be any python object. So you could do: raise FooException, ('descriptive text', error_code) > Are there other alternatives I should be considering? > Using an exception gives you the ability to handle similar errors in a similar way or the same error in different ways. try: if num_args != 6 and num_args != 4: raise ImproperArgs, (1, num_args) if 'badoption' in arg_list: # this would not be a static string raise ImproperArgs, (2, 'badoption') ... catch ImproperArgs, info: if info[0] == 1: print "Either 4 or 6 options expected, %d seen" % info[1] elsif info[0] == 2: print "This option is obsolete, %s" % info[1] print "Usage: blah blah" sys.exit(info[0]) Now the usage string appears only once localized to where it will be displayed. You could then wrap all of the initial arg checking in a function: settings = parse_args(sys.argv) try: settings = parse_args() catch ImproperArgs: ... From shalehperry@home.com Fri Oct 5 18:46:13 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Fri, 05 Oct 2001 10:46:13 -0700 (PDT) Subject: [Tutor] join syntax preferences Message-ID: So I mailed Danny griping at him for his recent response: def getContent(self): return '\n'.join(self.jscontent) I find this particular use of the new python string syntax annoying and against the clarity that we all know and love in python. My other complaint is this only works in 2.x and beyond so a person searching the archives or reading this list will be confused when this fails under 1.5 or earlier. So if we could strive to use syntax for all current python or at least give a dislaimer when something is new (or old). From lumbricus@gmx.net Fri Oct 5 18:58:14 2001 From: lumbricus@gmx.net (Joerg Woelke) Date: Fri, 5 Oct 2001 19:58:14 +0200 Subject: [Tutor] Treating program exceptions In-Reply-To: <590E1FF8B6A4D4118CB200508B63D23E020A6CB2@carussyrmb01.carrier.utc.com>; from Brad.Reisfeld@carrier.utc.com on Fri, Oct 05, 2001 at 09:45:51AM -0400 References: <590E1FF8B6A4D4118CB200508B63D23E020A6CB2@carussyrmb01.carrier.utc.com> Message-ID: <20011005195814.A14361@Laplace.localdomain> On Fri, Oct 05, 2001 at 09:45:51AM -0400, Reisfeld, Brad CAR wrote: > Hi, > I am wondering about the best way to flag out errors to my program's users > or calling programs. > > Possible as a holdover from my shell programming experience, I currently do > something like the following: > --- > (OKAY, NUM_PARAM_ERR, INVALID_PROP_ERR, DUP_PROP_ERR, INVALID_VAL_ERR, > OUT_OF_B\ > OUNDS_ERR, EMPTY_FILE_ERR, OUTPUT_ERR) = range(8) > import errno print errno.errorcode > arg_list = sys.argv IMHO there is no need for that. > prog_name = os.path.basename(arg_list.pop(0)) why not just sys.argv[0] > > if num_args != 6 and num_args != 4: len(sys.argv) man getopt ;-) > print "Error: Improper number of arguments." > print "Usage: %s property1 value1 property2 value2 [property3 value3]" % > (p\ > rog_name) > sys.exit(NUM_PARAM_ERR) $ cat ret.py #!/usr/bin/env python import errno import sys import os x="3.2" y="murks" def main(): try: float(x) float(y) ret=x/y except ValueError: print os.strerror(errno.EINVAL) sys.exit(errno.EINVAL) else: print "%.3f / %.3f = %.3f" %(x,y,ret) if __name__=="__main__": main() $ ./ret.py Das Argument ist ungültig $ echo $? 22 $ > > Any suggestions are appreciated. > > -Brad > HTH,HAND and Greetings J"o! -- A writer is congenitally unable to tell the truth and that is why we call what he writes fiction. -- William Faulkner From runsun@bilbo.bio.purdue.edu Fri Oct 5 20:00:03 2001 From: runsun@bilbo.bio.purdue.edu (Run-Sun Pan) Date: Fri, 5 Oct 2001 14:00:03 -0500 (EST) Subject: [Tutor] set/getattr and inheritance Message-ID: <200110051900.OAA08548@bilbo.bio.purdue.edu> Hi all, I am using the __setattr__ and __getattr__ pair to access variables of my class: #------------------------- class c_template(): myAddr = 'blahblahblah' class c_myclass(c_template): def __init__(self): self.__dict__['vars']={} self.vars['myName']='pan' def __setattr__(self,name,value): if not self.vars.has_key(name): raise AttributeError self.vars[name]=value def __getattr__(self,name): if not self.vars.has_key(name): raise AttributeError return self.vars[name] mc = c_myclass() mc.myName='panpan' mc.myAddr='blah' # trying to use the var of ancestor c_template #--------------------------- The last line of code raises an AttributeError. It's quite obvious that this .myAddr is not in the "vars" variable list of the current class (c_myclass), thus an error occurs. I can overcome this by redefining the c_myclass as: class c_myclass(c_template): def __init__(self): myName='pan' or simply: class c_myclass(c_template): myName='pan' which means, bypassing the usage of __setattr__, __getattr__ pairs. But then I can't utilize their functions to check the input values before they are assigned / obtained. Is there anyway to use these setattr/getattr pair yet still be able to access ancestor's variables ? thx in advance. pan From danny.kohn@systematik.se Fri Oct 5 20:49:02 2001 From: danny.kohn@systematik.se (Danny Kohn) Date: Fri, 5 Oct 2001 21:49:02 +0200 Subject: SV: SV: [Tutor] Stuck with classes - events In-Reply-To: Message-ID: | Fran: tutor-admin@python.org [mailto:tutor-admin@python.org]For Sean | 'Shaleh' Perry | Skickat: den 5 oktober 2001 16:46 | Till: Danny Kohn | Kopia: Python Tutor mailing list | Consider this. When item A gets a Ctrl+Left click it tells its=20 | parent to make it the current object. And how is this "telling" done in practice in oop? I am very new to = this. | The parent then makes item A the current=20 | object (gives | focus, etc). Essentially the object tells its controller "my=20 | turn please". |=20 | parent.givefocus(child) called from within child.handleKeyPress(). Again, yes this is what I want to do but I don't understand how to do = it. Could you elaborate slightly? How do I transfer control the way you = describe. Does it imply a special way of making classes and attributes? /Danny From shalehperry@home.com Fri Oct 5 21:03:24 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Fri, 05 Oct 2001 13:03:24 -0700 (PDT) Subject: SV: SV: [Tutor] Stuck with classes - events In-Reply-To: Message-ID: On 05-Oct-2001 Danny Kohn wrote: >| Fran: tutor-admin@python.org [mailto:tutor-admin@python.org]For Sean >| 'Shaleh' Perry >| Skickat: den 5 oktober 2001 16:46 >| Till: Danny Kohn >| Kopia: Python Tutor mailing list > >| Consider this. When item A gets a Ctrl+Left click it tells its >| parent to make it the current object. > > And how is this "telling" done in practice in oop? I am very new to this. > > Again, yes this is what I want to do but I don't understand how to do it. > Could you elaborate slightly? How do I transfer control the way you describe. > Does it imply a special way of making classes and attributes? > I am not familiar with wxPython. There should be a function call to give an object input focus. In my example, parent.givefocus() would call this function. This is not so much an OOP issue as it is understanding the capabilities of the library you are using. From shalehperry@home.com Fri Oct 5 21:06:30 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Fri, 05 Oct 2001 13:06:30 -0700 (PDT) Subject: [Tutor] set/getattr and inheritance In-Reply-To: <200110051900.OAA08548@bilbo.bio.purdue.edu> Message-ID: > > Is there anyway to use these setattr/getattr pair > yet still be able to access ancestor's variables ? > unfortuntely, no. getattr is only called if an AttributeError occurs. I am not sure if setattr is always called or not. From lkvam@venix.com Fri Oct 5 21:35:10 2001 From: lkvam@venix.com (Lloyd Kvam) Date: Fri, 05 Oct 2001 16:35:10 -0400 Subject: [Tutor] set/getattr and inheritance References: <200110051900.OAA08548@bilbo.bio.purdue.edu> Message-ID: <3BBE197E.3479CBBC@venix.com> You are responsible for managing the "inheritance" issues when you use __getattr__ and __setattr__. __setattr__ is the one that's very hard to get correct. I have cheated and used my own routine, normally called set, as an alternative to writing __setattr__. This set method then searches for the correct dictionary to use. setattr continues to work with the regular class dictionary. There may well be smarter solutions. Run-Sun Pan wrote: > > Hi all, > > I am using the __setattr__ and __getattr__ pair > to access variables of my class: > > #------------------------- > class c_template(): > myAddr = 'blahblahblah' > > class c_myclass(c_template): > def __init__(self): > self.__dict__['vars']={} > self.vars['myName']='pan' > > def __setattr__(self,name,value): > if not self.vars.has_key(name): raise AttributeError > self.vars[name]=value > > def __getattr__(self,name): > if not self.vars.has_key(name): raise AttributeError > return self.vars[name] > > mc = c_myclass() > mc.myName='panpan' > mc.myAddr='blah' # trying to use the var of ancestor c_template > #--------------------------- > > The last line of code raises an AttributeError. It's > quite obvious that this .myAddr is not in the "vars" > variable list of the current class (c_myclass), thus > an error occurs. > > I can overcome this by redefining the c_myclass as: > > class c_myclass(c_template): > def __init__(self): > myName='pan' > > or simply: > > class c_myclass(c_template): > myName='pan' > > which means, bypassing the usage of __setattr__, > __getattr__ pairs. But then I can't utilize their > functions to check the input values before they > are assigned / obtained. > > Is there anyway to use these setattr/getattr pair > yet still be able to access ancestor's variables ? > > thx in advance. > > pan > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From asdffdsa@bellatlantic.net Fri Oct 5 22:04:27 2001 From: asdffdsa@bellatlantic.net (David Meltzer) Date: Fri, 5 Oct 2001 17:04:27 -0400 Subject: [Tutor] ?4uplz-> function Message-ID: hilo2u and thanks for reading this, i would like to find a way to create a def that behaves more like a builtin keyword such as 'print' in that i would not need to use a parenthesis. here is an example print 10 //this is legal def printit(Num): print Num printit (10) //legal printit 10 //illegal. so perhaps you know a way to make the illegal legal thanks, dave From scarblac@pino.selwerd.nl Fri Oct 5 22:12:58 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Fri, 5 Oct 2001 23:12:58 +0200 Subject: [Tutor] ?4uplz-> function In-Reply-To: ; from asdffdsa@bellatlantic.net on Fri, Oct 05, 2001 at 05:04:27PM -0400 References: Message-ID: <20011005231258.A10191@pino.selwerd.nl> On 0, David Meltzer wrote: > hilo2u and thanks for reading this, > i would like to find a way to create a def that behaves more like a builtin > keyword such as 'print' in that i would not need to use a parenthesis. > > here is an example > > print 10 //this is legal > > def printit(Num): > print Num > > printit (10) //legal > printit 10 //illegal. > > so perhaps you know a way to make the illegal legal That's not possible. Only statements work like that, and you can't define new statements. -- Remco Gerlich From urnerk@qwest.net Fri Oct 5 22:16:07 2001 From: urnerk@qwest.net (Kirby Urner) Date: Fri, 05 Oct 2001 14:16:07 -0700 Subject: [Tutor] set/getattr and inheritance In-Reply-To: <200110051900.OAA08548@bilbo.bio.purdue.edu> Message-ID: <4.2.0.58.20011005134556.01a769a0@pop3.norton.antivirus> > >Is there anyway to use these setattr/getattr pair >yet still be able to access ancestor's variables ? > >thx in advance. > >pan A couple things: In creating 'vars' to store object attributes, and putting this in __dict__, you're somewhat redundantly duplicating the purpose of __dict__ itself, which is to keep the kind of info you're sticking in vars. So instead of: class c_myclass(c_template): def __init__(self): self.__dict__['vars']={} self.vars['myName']='pan' you could just go: def __init__(self): self.__dict__['myName'] ='pan' Then your __setattr__ method could check __dict__ directly: def __setattr__(self,name,value): if not self.__dict__.has_key(name): raise AttributeError self.__dict__[name]=value As a previous respondant pointed out, __getattr__ is invoked only if there's an attribute error, giving you some alternative way of handling the problem. To simply raise an attribute error in __getattr__ is unnecessary -- that's what Python would do for you anyway. Note that Python has no problem finding the base class attributes, and so doesn't invoke even touch your __getattr__ when you ask for mc.myAddr. It simply returns 'blahblahblah'. This might not be a problem, since "data validation" is something you'd do with __setattr__ but not __getattr__, i.e. to read a value already stored in the object shouldn't involve any validation. As for making your subclassed selves aware of base class attributes, you could update the instance dictionary with the name:value paires of the base class. If there's only one, you could do something like: def __init__(self): self.__dict__['myName'] ='pan' self.__dict__.update(self.__class__.__bases__[0].__dict__) This would let you change the local copy of myAddr, without affecting the baseclass value. New objects, instanced from c_myclass, would start with 'blahblahblah', even if mc had its own unique new value. Furthermore, changes at the base class level would not propagate to the instances, as in this scenario each was initialized with a local snapshot of the ancestor variables. If your goal is to make assignments to inherited properties trigger changes at the base class level, then I worry about the convoluted nature of this scheme. If you want some data validation at the ancestor class level, then why not put validations in the ancestor and inherit them? Also, I'm wondering if you are clear on the difference between class variables and instance variables. If the goal is to use the base class to initialize a bunch of default values, then why not move these initializations to the subclass as class variables and get rid of them in base class? For example, you could go: >>> class c_myclass: myAddr = 'blahblahblah' def __init__(self): self.__dict__['myName'] ='pan' self.__dict__['myAddr'] = c_myclass.myAddr def __setattr__(self,name,value): if not self.__dict__.has_key(name): raise AttributeError self.__dict__[name]=value >>> mc = c_myclass() >>> mc.myAddr 'blahblahblah' >>> mc.myAddr = 'duh' >>> mc.myAddr 'duh' >>> mc.myName = 'pan' >>> newmc = c_myclass() >>> newmc.myAddr 'blahblahblah' And so on. Kirby Kirby From urnerk@qwest.net Fri Oct 5 22:30:31 2001 From: urnerk@qwest.net (Kirby Urner) Date: Fri, 05 Oct 2001 14:30:31 -0700 Subject: [Tutor] ?4uplz-> function In-Reply-To: Message-ID: <4.2.0.58.20011005142829.01a7c220@pop3.norton.antivirus> At 05:04 PM 10/5/2001 -0400, David Meltzer wrote: >hilo2u and thanks for reading this, >i would like to find a way to create a def that behaves more like a builtin >keyword such as 'print' in that i would not need to use a parenthesis. I don't think so. Except at the operating system level you can go % printit 10 and have Python do something with 10 as an argument -- here printit is a Python script which invokes Python by means of #! at the top. But once inside the Python shell, I don't myself know of any way to get around the syntax of requiring ( ) after the function name. You're trying to change something very basic to Python. Kirby From dariob@millic.com.ar Sat Oct 6 01:16:11 2001 From: dariob@millic.com.ar (dariob@millic.com.ar) Date: Fri, 05 Oct 2001 21:16:11 -0300 Subject: [Tutor] VCD Y MP3. Message-ID: <0f72020090006a1MAIL2@smtp2.millic.com.ar> This is a Multipart MIME message. ------=_NextPart_000_001__2601650_76571,09 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 7bit ------=_NextPart_000_001__2601650_76571,09 Content-Type: text/html; charset=iso-8859-1 Content-Transfer-Encoding: base64 PGh0bWw+DQoNCjxoZWFkPg0KPG1ldGEgaHR0cC1lcXVpdj0iQ29udGVudC1MYW5ndWFnZSIg Y29udGVudD0iZXMiPg0KPG1ldGEgbmFtZT0iR0VORVJBVE9SIiBjb250ZW50PSJNaWNyb3Nv ZnQgRnJvbnRQYWdlIDUuMCI+DQo8bWV0YSBuYW1lPSJQcm9nSWQiIGNvbnRlbnQ9IkZyb250 UGFnZS5FZGl0b3IuRG9jdW1lbnQiPg0KPG1ldGEgaHR0cC1lcXVpdj0iQ29udGVudC1UeXBl IiBjb250ZW50PSJ0ZXh0L2h0bWw7IGNoYXJzZXQ9d2luZG93cy0xMjUyIj4NCjx0aXRsZT5Q YWdpbmEgbnVldmEgMTwvdGl0bGU+DQo8L2hlYWQ+DQoNCjxib2R5Pg0KDQo8dGFibGUgaGVp Z2h0PSI4MSIgY2VsbFNwYWNpbmc9IjAiIGNlbGxQYWRkaW5nPSIwIiB3aWR0aD0iMTAwJSIg YmdDb2xvcj0iIzAwMDAwMCIgYm9yZGVyPSIwIj4NCiAgPGZvbnQgZmFjZT0iQXJpYWwsIEhl bHZldGljYSwgc2Fucy1zZXJpZiIgY29sb3I9IiMwMDgwZmYiIHNpemU9IjQiPjxiPg0KICA8 Y2FwdGlvbj48Zm9udCBmYWNlPSJUYWhvbWEiIGNvbG9yPSIjZmYwMDAwIiBzaXplPSI2Ij48 c3Ryb25nPqGhoaEgTk8gVEUgUE9ERVMgDQogIFBFUkRFUiBFU1RBIE9QT1JUVU5JREFEISEh ITwvc3Ryb25nPjwvZm9udD4gPHN0cm9uZz4NCiAgPGZvbnQgZmFjZT0iVGFob21hIiBjb2xv cj0iIzAwMDBmZiIgc2l6ZT0iNSI+PGZvbnQgc2l6ZT0iNSIgZmFjZT0iVGFob21hIj4NCiAg RVNDVUNIQSA8L2ZvbnQ+PC9mb250Pjwvc3Ryb25nPjxmb250IHNpemU9IisyIiBjb2xvcj0i IzAwMDBmZiIgZmFjZT0iVGFob21hIj4NCiAgTdpTSUNBIE1QMyBFTiBUVSBBVVRPLCBDQVNB LCBDQU1JTkFORE8gTyBFTiBET05ERSBQUkVGSUVSQVMsPC9mb250PjxzdHJvbmc+PGZvbnQg ZmFjZT0iVGFob21hIiBjb2xvcj0iIzAwMDBmZiIgc2l6ZT0iNSI+PGZvbnQgc2l6ZT0iNSIg ZmFjZT0iVGFob21hIj4NCiAgWSBNSVJBIExBUyBNRUpPUkVTIDwvZm9udD48Zm9udCBzaXpl PSI1IiBmYWNlPSJUYWhvbWEiPg0KICBQRUzNQ1VMQVMgRU4gRUwgVFYgREUgVFUgQ0FTQS48 L2ZvbnQ+PC9mb250Pjwvc3Ryb25nPg0KICA8Zm9udCBmYWNlPSJUYWhvbWEiIGNvbG9yPSIj MDAwMGZmIiBzaXplPSI1Ij48c3Ryb25nPjx1PlPaUEVSIE9GRVJUQSBFTiBMQSANCiAgUFVF UlRBIERFIFRVIENBU0E8L3U+PC9zdHJvbmc+PC9mb250PjwvYj48L2ZvbnQ+DQogIDxwIGFs aWduPSJjZW50ZXIiPg0KICA8Zm9udCBmYWNlPSJBcmlhbCwgSGVsdmV0aWNhLCBzYW5zLXNl cmlmIiBjb2xvcj0iIzAwODBmZiIgc2l6ZT0iNCI+PGI+TG8gTWVqb3IgDQogIGRlbCBNZXJj YWRvIGEgUHJlY2lvIGRlIExPQ09TPC9iPjwvZm9udD48L3A+DQogIDwvY2FwdGlvbj4NCiAg PHRyPg0KICAgIDx0ZCBoZWlnaHQ9IjgxIj4NCiAgICA8dGFibGUgY2VsbFNwYWNpbmc9IjAi IGNlbGxQYWRkaW5nPSI2IiB3aWR0aD0iMTAwJSIgYm9yZGVyPSIwIiBoZWlnaHQ9IjcxIj4N CiAgICAgIDx0cj4NCiAgICAgICAgPHRkIHdpZHRoPSI1MyUiIGhlaWdodD0iNTkiPg0KICAg ICAgICA8dGFibGUgY2VsbFNwYWNpbmc9IjAiIGNlbGxQYWRkaW5nPSIzIiB3aWR0aD0iMTAw JSIgYmdDb2xvcj0iIzAwODAwMCIgYm9yZGVyPSIwIj4NCiAgICAgICAgICA8dHI+DQogICAg ICAgICAgICA8dGQgd2lkdGg9IjEwMCUiPg0KICAgICAgICAgICAgPHAgc3R5bGU9IndvcmQt c3BhY2luZzogMHB4OyBtYXJnaW4tbGVmdDogMHB4OyBtYXJnaW4tcmlnaHQ6IDBweDsgbWFy Z2luLXRvcDogMHB4OyBtYXJnaW4tYm90dG9tOiA2cHgiIGFsaWduPSJjZW50ZXIiPg0KICAg ICAgICAgICAgPGZvbnQgZmFjZT0iQXJpYWwgQmxhY2siIGNvbG9yPSIjZmZmZjAwIj5PZmVy dGEgbGltaXRhZGEsIGhhc3RhIA0KICAgICAgICAgICAgYWdvdGFyIFN0b2NrLjwvZm9udD48 L3A+DQogICAgICAgICAgICA8cCBzdHlsZT0id29yZC1zcGFjaW5nOiAwcHg7IG1hcmdpbi1s ZWZ0OiAwcHg7IG1hcmdpbi1yaWdodDogMHB4OyBtYXJnaW4tdG9wOiAwcHg7IG1hcmdpbi1i b3R0b206IDZweCIgYWxpZ249ImNlbnRlciI+DQogICAgICAgICAgICA8Yj48Zm9udCBmYWNl PSJBcmlhbCIgY29sb3I9IiNmZmZmMDAiIHNpemU9IjIiPk11Y2hvcyB5YSBsbyB0aWVuZW4s IA0KICAgICAgICAgICAgZXN0YSBvcG9ydHVuaWRhZCBubyBzZSByZXBldGly4SB5IGxhcyB1 bmlkYWRlcyBzZSBlc3RhbiBhY2FiYW5kbywgbm8gDQogICAgICAgICAgICBzZSB2ZW5kZSBw b3Igb3RybyBtZWRpbywgaGF6IHR1IG9mZXJ0YSBwdWVzIG1h8WFuYSBwdWVkZSBzZXIgdGFy ZGUuPC9mb250PjwvYj48L3RkPg0KICAgICAgICAgIDwvdHI+DQogICAgICAgIDwvdGFibGU+ DQogICAgICAgIDwvdGQ+DQogICAgICA8L3RyPg0KICAgIDwvdGFibGU+DQogICAgPC90ZD4N CiAgPC90cj4NCjwvdGFibGU+DQo8dGFibGUgaGVpZ2h0PSIxNTQiIGNlbGxTcGFjaW5nPSIw IiBjZWxsUGFkZGluZz0iMCIgd2lkdGg9IjU4NCIgYm9yZGVyPSIwIj4NCiAgPHRyPg0KICAg IDx0ZCB2QWxpZ249InRvcCIgd2lkdGg9IjI3MSIgaGVpZ2h0PSIxNTQiPg0KICAgIDx0YWJs ZSBoZWlnaHQ9IjQxNSIgY2VsbFNwYWNpbmc9IjAiIGNlbGxQYWRkaW5nPSIwIiB3aWR0aD0i MjA3IiBib3JkZXI9IjAiPg0KICAgICAgPHRyPg0KICAgICAgICA8dGQgd2lkdGg9IjE5NyIg aGVpZ2h0PSI0MTUiPg0KICAgICAgICA8dGFibGUgYm9yZGVyQ29sb3I9IiMwMDgwZmYiIGhl aWdodD0iMzQxIiBjZWxsU3BhY2luZz0iMCIgY2VsbFBhZGRpbmc9IjAiIHdpZHRoPSIxMDAl IiBib3JkZXI9IjIiPg0KICAgICAgICAgIDx0cj4NCiAgICAgICAgICAgIDx0ZCB3aWR0aD0i MTAwJSIgaGVpZ2h0PSIzMSI+DQogICAgICAgICAgICA8dGFibGUgY2VsbFNwYWNpbmc9IjAi IGNlbGxQYWRkaW5nPSI1IiB3aWR0aD0iMTAwJSIgYmdDb2xvcj0iIzAwODBmZiIgYm9yZGVy PSIwIj4NCiAgICAgICAgICAgICAgPHRyPg0KICAgICAgICAgICAgICAgIDx0ZCB3aWR0aD0i MTAwJSI+PGZvbnQgZmFjZT0iVGFob21hIiBjb2xvcj0iI2ZmZmZmZiIgc2l6ZT0iMyI+DQog ICAgICAgICAgICAgICAgPGI+Q2FyYWN0ZXLtc3RpY2FzPC9iPjwvZm9udD48L3RkPg0KICAg ICAgICAgICAgICA8L3RyPg0KICAgICAgICAgICAgPC90YWJsZT4NCiAgICAgICAgICAgIDwv dGQ+DQogICAgICAgICAgPC90cj4NCiAgICAgICAgICA8dHI+DQogICAgICAgICAgICA8dGQg d2lkdGg9IjEwMCUiIGhlaWdodD0iMzA2Ij4NCiAgICAgICAgICAgIDx0YWJsZSBoZWlnaHQ9 IjMwMiIgY2VsbFNwYWNpbmc9IjAiIGNlbGxQYWRkaW5nPSI1IiB3aWR0aD0iMTAwJSIgYm9y ZGVyPSIwIj4NCiAgICAgICAgICAgICAgPHRyPg0KICAgICAgICAgICAgICAgIDx0ZCB3aWR0 aD0iMTAwJSIgaGVpZ2h0PSIyOTYiPg0KICAgICAgICAgICAgICAgIDx0YWJsZSBjZWxsU3Bh Y2luZz0iMCIgY2VsbFBhZGRpbmc9IjAiIHdpZHRoPSIxMDAlIiBib3JkZXI9IjAiPg0KICAg ICAgICAgICAgICAgICAgPHRyPg0KICAgICAgICAgICAgICAgICAgICA8dGQgd2lkdGg9IjEw MCUiPg0KICAgICAgICAgICAgICAgICAgICA8cCBzdHlsZT0id29yZC1zcGFjaW5nOiAwcHg7 IG1hcmdpbi1sZWZ0OiAwcHg7IG1hcmdpbi1yaWdodDogMHB4OyBtYXJnaW4tdG9wOiAwcHg7 IG1hcmdpbi1ib3R0b206IDVweCI+DQogICAgICAgICAgICAgICAgICAgIDxmb250IGZhY2U9 IlRhaG9tYSIgY29sb3I9IiMwMDgwZmYiIHNpemU9IjIiPjxiPlVuaWNvIGVuIA0KICAgICAg ICAgICAgICAgICAgICBBcmdlbnRpbmEgcXVlIGxlZSBjZCBjb24gTVAzIHkgYWRlbWFzIGxl ZSBWQ0QgY29uIHNhbGlkYSBkZSANCiAgICAgICAgICAgICAgICAgICAgdmlkZW8geSBhdWRp byBvIHNlYSBxdWUmbmJzcDtzZSB2ZW4gZW4gZWwgdGVsZXZpc29yLCBlcyBsbyB1bHRpbW8g DQogICAgICAgICAgICAgICAgICAgIGVuIHRlY25vbG9naWEgcGFyYSBtcDMgeSB2Y2Q8L2I+ PC9mb250PjwvcD4NCiAgICAgICAgICAgICAgICAgICAgPHAgc3R5bGU9IndvcmQtc3BhY2lu ZzogMHB4OyBtYXJnaW4tbGVmdDogMHB4OyBtYXJnaW4tcmlnaHQ6IDBweDsgbWFyZ2luLXRv cDogMHB4OyBtYXJnaW4tYm90dG9tOiA1cHgiPg0KICAgICAgICAgICAgICAgICAgICA8Zm9u dCBmYWNlPSJUYWhvbWEiIGNvbG9yPSIjMDA4MGZmIiBzaXplPSIyIj48Yj5FbCANCiAgICAg ICAgICAgICAgICAgICAgcmVwcm9kdWN0b3IgZGUgTVAzIHkgVkNEIGluY2x1eWU6PC9iPjwv Zm9udD48L3A+DQogICAgICAgICAgICAgICAgICAgIDxwIHN0eWxlPSJ3b3JkLXNwYWNpbmc6 IDBweDsgbWFyZ2luLWxlZnQ6IDBweDsgbWFyZ2luLXJpZ2h0OiAwcHg7IG1hcmdpbi10b3A6 IDBweDsgbWFyZ2luLWJvdHRvbTogNXB4Ij4NCiAgICAgICAgICAgICAgICAgICAgPGZvbnQg ZmFjZT0iVGFob21hIiBjb2xvcj0iIzAwODBmZiIgc2l6ZT0iMiI+PGI+LSBDb250cm9sIA0K ICAgICAgICAgICAgICAgICAgICByZW1vdG8gaW5hbGFtYnJpY288L2I+PC9mb250PjwvcD4N CiAgICAgICAgICAgICAgICAgICAgPHAgc3R5bGU9IndvcmQtc3BhY2luZzogMHB4OyBtYXJn aW4tbGVmdDogMHB4OyBtYXJnaW4tcmlnaHQ6IDBweDsgbWFyZ2luLXRvcDogMHB4OyBtYXJn aW4tYm90dG9tOiA1cHgiPg0KICAgICAgICAgICAgICAgICAgICA8Zm9udCBmYWNlPSJUYWhv bWEiIGNvbG9yPSIjMDA4MGZmIiBzaXplPSIyIj48Yj4tIEJhdGVyaWFzIA0KICAgICAgICAg ICAgICAgICAgICAoUGlsYXMpIFJlY2FyZ2FibGVzIExpdGl1bTwvYj48L2ZvbnQ+PC9wPg0K ICAgICAgICAgICAgICAgICAgICA8cCBzdHlsZT0id29yZC1zcGFjaW5nOiAwcHg7IG1hcmdp bi1sZWZ0OiAwcHg7IG1hcmdpbi1yaWdodDogMHB4OyBtYXJnaW4tdG9wOiAwcHg7IG1hcmdp bi1ib3R0b206IDVweCI+DQogICAgICAgICAgICAgICAgICAgIDxmb250IGZhY2U9IlRhaG9t YSIgY29sb3I9IiMwMDgwZmYiIHNpemU9IjIiPjxiPi0gQ2FibGVzIGRlIA0KICAgICAgICAg ICAgICAgICAgICBBdWRpbyB5IGRlIFZpZGVvPC9iPjwvZm9udD48L3A+DQogICAgICAgICAg ICAgICAgICAgIDxwIHN0eWxlPSJ3b3JkLXNwYWNpbmc6IDBweDsgbWFyZ2luLWxlZnQ6IDBw eDsgbWFyZ2luLXJpZ2h0OiAwcHg7IG1hcmdpbi10b3A6IDBweDsgbWFyZ2luLWJvdHRvbTog NXB4Ij4NCiAgICAgICAgICAgICAgICAgICAgPGZvbnQgZmFjZT0iVGFob21hIiBjb2xvcj0i IzAwODBmZiIgc2l6ZT0iMiI+PGI+LSBBdWRpZm9ubzwvYj48L2ZvbnQ+PC9wPg0KICAgICAg ICAgICAgICAgICAgICA8cCBzdHlsZT0id29yZC1zcGFjaW5nOiAwcHg7IG1hcmdpbi1sZWZ0 OiAwcHg7IG1hcmdpbi1yaWdodDogMHB4OyBtYXJnaW4tdG9wOiAwcHg7IG1hcmdpbi1ib3R0 b206IDVweCI+DQogICAgICAgICAgICAgICAgICAgIDxmb250IGZhY2U9IlRhaG9tYSIgY29s b3I9IiMwMDgwZmYiIHNpemU9IjIiPjxiPi0gTWFudWFsIGRlIA0KICAgICAgICAgICAgICAg ICAgICBpbnN0cnVjY2lvbjwvYj48L2ZvbnQ+PC9wPg0KICAgICAgICAgICAgICAgICAgICA8 cCBzdHlsZT0id29yZC1zcGFjaW5nOiAwcHg7IG1hcmdpbi1sZWZ0OiAwcHg7IG1hcmdpbi1y aWdodDogMHB4OyBtYXJnaW4tdG9wOiAwcHg7IG1hcmdpbi1ib3R0b206IDVweCI+DQogICAg ICAgICAgICAgICAgICAgIDxmb250IGZhY2U9IlRhaG9tYSIgY29sb3I9IiMwMDgwZmYiIHNp emU9IjIiPjxiPi0gDQogICAgICAgICAgICAgICAgICAgIFRyYW5zZm9ybWFkb3I8L2I+PC9m b250PjwvcD4NCiAgICAgICAgICAgICAgICAgICAgPHAgc3R5bGU9IndvcmQtc3BhY2luZzog MHB4OyBtYXJnaW4tbGVmdDogMHB4OyBtYXJnaW4tcmlnaHQ6IDBweDsgbWFyZ2luLXRvcDog MHB4OyBtYXJnaW4tYm90dG9tOiA1cHgiPg0KICAgICAgICAgICAgICAgICAgICA8Zm9udCBm YWNlPSJUYWhvbWEiIGNvbG9yPSIjMDA4MGZmIiBzaXplPSIyIj48Yj4tIENhcmdhZG9yPC9i PjwvZm9udD48L3RkPg0KICAgICAgICAgICAgICAgICAgPC90cj4NCiAgICAgICAgICAgICAg ICA8L3RhYmxlPg0KICAgICAgICAgICAgICAgIDwvdGQ+DQogICAgICAgICAgICAgIDwvdHI+ DQogICAgICAgICAgICA8L3RhYmxlPg0KICAgICAgICAgICAgPC90ZD4NCiAgICAgICAgICA8 L3RyPg0KICAgICAgICA8L3RhYmxlPg0KICAgICAgICA8L3RkPg0KICAgICAgPC90cj4NCiAg ICA8L3RhYmxlPg0KICAgIDwvdGQ+DQogICAgPHRkIHdpZHRoPSIzMjciIGhlaWdodD0iMTU0 Ij4NCiAgICA8dGFibGUgY2VsbFNwYWNpbmc9IjAiIGNlbGxQYWRkaW5nPSIwIiB3aWR0aD0i MTAwJSIgYm9yZGVyPSIwIj4NCiAgICAgIDx0cj4NCiAgICAgICAgPHRkIHdpZHRoPSIxMDAl Ij4NCiAgICAgICAgPHRhYmxlIGNlbGxTcGFjaW5nPSIwIiBjZWxsUGFkZGluZz0iMCIgd2lk dGg9IjEwMCUiIGJvcmRlcj0iMCI+DQogICAgICAgICAgPHRyPg0KICAgICAgICAgICAgPHRk IHdpZHRoPSI3MiUiPg0KICAgICAgICAgICAgPGltZyBoZWlnaHQ9IjIxMiIgc3JjPSJodHRw Oi8vaW1hZ2Vob3N0LmF1Y3Rpb253YXRjaC5jb20vcHJldmlldy9jYy9jY29ycmVhL21wdHJl cDUuanBnIiB3aWR0aD0iMjIyIiBib3JkZXI9IjAiPjwvdGQ+DQogICAgICAgICAgICA8dGQg d2lkdGg9IjI4JSI+DQogICAgICAgICAgICA8dGFibGUgY2VsbFNwYWNpbmc9IjAiIGNlbGxQ YWRkaW5nPSIwIiB3aWR0aD0iMTAwJSIgYm9yZGVyPSIwIj4NCiAgICAgICAgICAgICAgPHRy Pg0KICAgICAgICAgICAgICAgIDx0ZCB3aWR0aD0iMTAwJSI+DQogICAgICAgICAgICAgICAg PGltZyBzcmM9Imh0dHA6Ly9pbWFnZWhvc3QuYXVjdGlvbndhdGNoLmNvbS9wcmV2aWV3L2Nj L2Njb3JyZWEvbXB0cmVwMS5qcGciIHdpZHRoPSIxMjYiIGJvcmRlcj0iMCI+PC90ZD4NCiAg ICAgICAgICAgICAgPC90cj4NCiAgICAgICAgICAgICAgPHRyPg0KICAgICAgICAgICAgICAg IDx0ZCB3aWR0aD0iMTAwJSI+DQogICAgICAgICAgICAgICAgPGltZyBzcmM9Imh0dHA6Ly9p bWFnZWhvc3QuYXVjdGlvbndhdGNoLmNvbS9wcmV2aWV3L2NjL2Njb3JyZWEvbXB0cmVwMi5q cGciIHdpZHRoPSIxMjYiIGJvcmRlcj0iMCI+PC90ZD4NCiAgICAgICAgICAgICAgPC90cj4N CiAgICAgICAgICAgICAgPHRyPg0KICAgICAgICAgICAgICAgIDx0ZCB3aWR0aD0iMTAwJSI+ DQogICAgICAgICAgICAgICAgPGltZyBzcmM9Imh0dHA6Ly9pbWFnZWhvc3QuYXVjdGlvbndh dGNoLmNvbS9wcmV2aWV3L2NjL2Njb3JyZWEvbXB0cmVwNy5qcGciIHdpZHRoPSIxMjYiIGJv cmRlcj0iMCI+PC90ZD4NCiAgICAgICAgICAgICAgPC90cj4NCiAgICAgICAgICAgICAgPHRy Pg0KICAgICAgICAgICAgICAgIDx0ZCB3aWR0aD0iMTAwJSI+DQogICAgICAgICAgICAgICAg PGltZyBzcmM9Imh0dHA6Ly9pbWFnZWhvc3QuYXVjdGlvbndhdGNoLmNvbS9wcmV2aWV3L2Nj L2Njb3JyZWEvbXB0cmVwOC5qcGciIHdpZHRoPSIxMjYiIGJvcmRlcj0iMCI+PC90ZD4NCiAg ICAgICAgICAgICAgPC90cj4NCiAgICAgICAgICAgIDwvdGFibGU+DQogICAgICAgICAgICA8 L3RkPg0KICAgICAgICAgIDwvdHI+DQogICAgICAgIDwvdGFibGU+DQogICAgICAgIDwvdGQ+ DQogICAgICA8L3RyPg0KICAgICAgPHRyPg0KICAgICAgICA8dGQgd2lkdGg9IjEwMCUiPg0K ICAgICAgICA8dGFibGUgY2VsbFNwYWNpbmc9IjAiIGNlbGxQYWRkaW5nPSIwIiB3aWR0aD0i MTAwJSIgYm9yZGVyPSIwIj4NCiAgICAgICAgICA8dHI+DQogICAgICAgICAgICA8dGQgd2lk dGg9IjUwJSI+DQogICAgICAgICAgICA8aW1nIGhlaWdodD0iMTMyIiBzcmM9Imh0dHA6Ly9p bWFnZWhvc3QuYXVjdGlvbndhdGNoLmNvbS9wcmV2aWV3L2NjL2Njb3JyZWEvbXB0cmVwMy5q cGciIHdpZHRoPSIxNjMiIGJvcmRlcj0iMCI+PC90ZD4NCiAgICAgICAgICAgIDx0ZCB3aWR0 aD0iNTAlIj4NCiAgICAgICAgICAgIDxpbWcgaGVpZ2h0PSIxMzMiIHNyYz0iaHR0cDovL2lt YWdlaG9zdC5hdWN0aW9ud2F0Y2guY29tL3ByZXZpZXcvY2MvY2NvcnJlYS9tcHRyZXA2Lmpw ZyIgd2lkdGg9IjE2OCIgYm9yZGVyPSIwIj48L3RkPg0KICAgICAgICAgIDwvdHI+DQogICAg ICAgIDwvdGFibGU+DQogICAgICAgIDwvdGQ+DQogICAgICA8L3RyPg0KICAgIDwvdGFibGU+ DQogICAgPC90ZD4NCiAgPC90cj4NCjwvdGFibGU+DQo8dGFibGUgaGVpZ2h0PSI0MCIgY2Vs bFNwYWNpbmc9IjAiIGNlbGxQYWRkaW5nPSIwIiB3aWR0aD0iNTg0IiBib3JkZXI9IjAiPg0K ICA8dHI+DQogICAgPHRkIGhlaWdodD0iNDAiPg0KICAgIDx0YWJsZSBjZWxsU3BhY2luZz0i MCIgY2VsbFBhZGRpbmc9IjAiIHdpZHRoPSIxMDAlIiBib3JkZXI9IjAiPg0KICAgICAgPHRy Pg0KICAgICAgICA8dGQgd2lkdGg9IjEwMCUiPg0KICAgICAgICA8dGFibGUgY2VsbFNwYWNp bmc9IjAiIGNlbGxQYWRkaW5nPSI1IiB3aWR0aD0iMTAwJSIgYmdDb2xvcj0iIzAwODBmZiIg Ym9yZGVyPSIwIj4NCiAgICAgICAgICA8dHI+DQogICAgICAgICAgICA8dGQgd2lkdGg9IjEw MCUiPjxiPjxmb250IGZhY2U9IlRhaG9tYSIgY29sb3I9IiNmZmZmZmYiIHNpemU9IjMiPg0K ICAgICAgICAgICAgRXNwZWNpZmljYWNpb25lcyB0ZWNuaWNhczwvZm9udD48L2I+PC90ZD4N CiAgICAgICAgICA8L3RyPg0KICAgICAgICA8L3RhYmxlPg0KICAgICAgICA8L3RkPg0KICAg ICAgPC90cj4NCiAgICAgIDx0cj4NCiAgICAgICAgPHRkIHdpZHRoPSIxMDAlIj4NCiAgICAg ICAgPHRhYmxlIGNlbGxTcGFjaW5nPSIwIiBjZWxsUGFkZGluZz0iNSIgd2lkdGg9IjEwMCUi IGJvcmRlcj0iMCI+DQogICAgICAgICAgPHRyPg0KICAgICAgICAgICAgPHRkIHdpZHRoPSI1 MCUiPjxiPjxmb250IGZhY2U9IlRhaG9tYSIgY29sb3I9IiMwMDgwZmYiIHNpemU9IjIiPg0K ICAgICAgICAgICAgU3Vtc3VuZyBMZW5zPGJyPg0KICAgICAgICAgICAgU29ueSBTZXJ2byBz eXN0ZW08YnI+DQogICAgICAgICAgICBTdXBwb3J0IFJlZ3VsYXIgQXVkaW8sIE1QMyxWQ0Qs RFZDRCw4MCBtaW4gQ0QtUixDRC1SVyBhbmQgOCBjbSBDRC1SIA0KICAgICAgICAgICAgZGlz Yzxicj4NCiAgICAgICAgICAgIGNvbXBhdGlibGUgVkNEIDIuMCwzLjAgYW5kIERWQ0QgZGlz Yzxicj4NCiAgICAgICAgICAgIDYgViBwb3dlciBvdXRwdXQ8YnI+DQogICAgICAgICAgICBi dWlsZC1pbiByZWNoYXJnZWFibGUgbGl0aGl1bSBiYXR0ZXJ5PGJyPg0KICAgICAgICAgICAg Q29uc3VtcHRpb24gb2YgYmF0dGVyeSAoc2kgZXMgcXVlIG5vIGxhIG9yaWdpbmFsKSAyLjUg LSAzIGhvdXJzIGZvciANCiAgICAgICAgICAgIE1QMyBkaXNjPGJyPg0KICAgICAgICAgICAg MS41IC0gMiBob3VycyBmb3IgVkNEIGRpc2M8YnI+DQombmJzcDs8L2ZvbnQ+PC9iPjwvdGQ+ DQogICAgICAgICAgICA8dGQgd2lkdGg9IjUwJSI+PGI+PGZvbnQgZmFjZT0iVGFob21hIiBj b2xvcj0iIzAwODBmZiIgc2l6ZT0iMiI+DQogICAgICAgICAgICBBY2Nlc3Nvcmllczo8YnI+ DQogICAgICAgICAgICBQb3dlciBzdXBwbHkoMTAwViAtIDI0MFYpPGJyPg0KICAgICAgICAg ICAgSW5zdHJ1Y3Rpb24gbWFudWFsPGJyPg0KICAgICAgICAgICAgRWFycGhvbmU8YnI+DQog ICAgICAgICAgICBSZWNoYXJnZWFibGUgTGl0aGl1bSBiYXR0ZXJpZXM8YnI+DQogICAgICAg ICAgICBBL1YgQ2FibGU8YnI+DQogICAgICAgICAgICBSZW1vdGUgY29udHJvbDxicj4NCiAg ICAgICAgICAgIEVzdGFzIHNvbiBsYXMgbm9ybWFzIGEgbGFzIHF1ZSBzZSBzb21ldGllcm9u IHkgcGFzYXJvbiBlc3RvIGF2YWxhIGxhIA0KICAgICAgICAgICAgY2FsaWRhZDxicj4NCiAg ICAgICAgICAgIGFwcHJvdmFsOiBGQ0MsIFVMLCBGREEsIENFLCBDQ0VFPC9mb250PjwvYj48 L3RkPg0KICAgICAgICAgIDwvdHI+DQogICAgICAgIDwvdGFibGU+DQogICAgICAgIDwvdGQ+ DQogICAgICA8L3RyPg0KICAgIDwvdGFibGU+DQogICAgPGRpdiBhbGlnbj0iY2VudGVyIj4N CiAgICAgIDxmb250IGZhY2U9IlRhaG9tYSIgc2l6ZT0iNSI+PHN0cm9uZz5Db24gbGEgY29t cHJhIGRlbCBT+nBlciBEaXNjbWFuIHRlIA0KICAgICAgbGxldmFzIGRlIHJlZ2FsbyA8L3N0 cm9uZz48L2ZvbnQ+DQogICAgPC9kaXY+DQogICAgPGRpdiBhbGlnbj0iY2VudGVyIj4NCiAg ICAgIDxmb250IGZhY2U9IlRhaG9tYSIgc2l6ZT0iNSI+PHN0cm9uZz51bmEgcOlsaWN1bGEg eSB1biBDRCBkZSBtcDMgYSANCiAgICAgIGVsZWNjafNuLjwvc3Ryb25nPjwvZm9udD48L2Rp dj4NCiAgICA8ZGl2IGFsaWduPSJjZW50ZXIiPg0KICAgICAgPGRpdiBhbGlnbj0iY2VudGVy Ij4NCiAgICAgICAgPGZvbnQgZmFjZT0iVGFob21hIiBjb2xvcj0iIzgwMDA4MCIgc2l6ZT0i NSI+PHN0cm9uZz4oTk8gVEUgUE9ERVMgUFJJVkFSIA0KICAgICAgICBERSBMQVMgTUVKT1JF UyBDT1NBUyk8L3N0cm9uZz48L2ZvbnQ+PC9kaXY+DQogICAgPC9kaXY+DQogICAgPC90ZD4N CiAgPC90cj4NCjwvdGFibGU+DQo8cD48Zm9udCBzaXplPSIrMiIgY29sb3I9IiM4MDAwODAi IGZhY2U9IlRhaG9tYSI+Jm5ic3A7Jm5ic3A7Jm5ic3A7Jm5ic3A7Jm5ic3A7Jm5ic3A7Jm5i c3A7Jm5ic3A7Jm5ic3A7Jm5ic3A7Jm5ic3A7Jm5ic3A7Jm5ic3A7Jm5ic3A7Jm5ic3A7Jm5i c3A7Jm5ic3A7Jm5ic3A7IA0KRU5WSU9TIEEgVE9ETyBFTCBQQUlTPC9mb250PjwvcD4NCjxw Pjxmb250IHNpemU9IisyIiBjb2xvcj0iIzgwMDA4MCIgZmFjZT0iVGFob21hIj5QQVJBIE1B UyANCklORk9STUFDSU9OIFNPTE8gRU5WSUEgVU4gTUFJTCBBPC9mb250PjxzdHJvbmc+PGZv bnQgZmFjZT0iVGFob21hIiBzaXplPSI1IiBjb2xvcj0iIzgwMDA4MCI+DQo8YSBocmVmPSJt YWlsdG86ZGFyaW9iZXJAc3BlZWR5LmNvbS5hciI+ZGFyaW9iZXJAc3BlZWR5LmNvbS5hcjwv YT48L2ZvbnQ+PC9zdHJvbmc+PC9wPg0KDQo8L2JvZHk+DQoNCjwvaHRtbD4= ------=_NextPart_000_001__2601650_76571,09-- From urnerk@qwest.net Sat Oct 6 19:21:13 2001 From: urnerk@qwest.net (Kirby Urner) Date: Sat, 06 Oct 2001 11:21:13 -0700 Subject: [Tutor] set/getattr and inheritance In-Reply-To: <4.2.0.58.20011005134556.01a769a0@pop3.norton.antivirus> References: <200110051900.OAA08548@bilbo.bio.purdue.edu> Message-ID: <4.2.0.58.20011006111909.019bcf00@pop3.norton.antivirus> Note: starting with Python 2.2, there's a whole other way to define set and get methods, using the new builtin 'property'. Here's an example, based on the example given in the tutorial at http://www.python.org/2.2/descrintro.html#property (itself nothing more than an example): >>> class C(object): def __init__(self): self.__x = None self.__y = None def getx(self): return self.__x def setx(self,val): if not str(val) in string.uppercase: print "Nope" else: self.__x = val def gety(self): return self.__y def sety(self,val): if not str(val) in string.digits: print "Nope" else: self.__y = val x = property(getx, setx) y = property(gety, sety) >>> o = C() >>> o.y = 1 >>> o.y 1 >>> o.y = 'A' Nope >>> o.x = 'a' Nope >>> o.x = 'A' >>> o.x 'A' Kirby From tor@stormwall.org Fri Oct 5 19:51:32 2001 From: tor@stormwall.org (Tor Stormwall) Date: Fri, 05 Oct 2001 20:51:32 +0200 Subject: [Tutor] A command line Message-ID: <3BBE0134.DC8E02BF@stormwall.org> Hi! I'm trying make a little interpreter that will other run commands. But why cant I do like this: import os import sys def commands(): if sys.argv[0] == open: print "opening" elif sys.argv[0] == exit: sys.exit() else: print "not a valid command" def interpreter(prompt='=> '): try: while 1: command = raw_input(prompt) try: #flag = os.system('echo Hej') if command: commands() # calling "def commands()" except (IndexError, KeyError): print "'%s' not a valid command" % command else: pass except EOFError: pass interpreter() Best Regards, Tor Stormwall -- * - - - - - - - - - - - - - - - - - - - - - - - - - - - - * | M A Y T H E S O U R C E B E W I T H Y O U | | | | Tor Stormwall mailto:tor@stormwall.org | | http://www.creson.com/~tor | | | | http://www.sslug.dk http://www.stormwall.org | | http://www.FreeBSD.org http://www.muf.se | | | * - - - - - - - - - - - - - - - - - - - - - - - - - - - - * From urnerk@qwest.net Sat Oct 6 20:42:45 2001 From: urnerk@qwest.net (Kirby Urner) Date: Sat, 06 Oct 2001 12:42:45 -0700 Subject: [Tutor] A command line In-Reply-To: <3BBE0134.DC8E02BF@stormwall.org> Message-ID: <4.2.0.58.20011006121024.019b0910@pop3.norton.antivirus> At 08:51 PM 10/5/2001 +0200, Tor Stormwall wrote: >Hi! > >I'm trying make a little interpreter that will other run >commands. > >But why cant I do like this: The sys.argv stuff is for capturing arguments passed to Python from the operating system shell, not from the Python shell. If you're already in Python, then you just want to pass your argument to commands directly, like this: >>> def commands(commline): if commline == "open": print "opening" return 1 elif commline == "exit": return 0 else: print "not a valid command" return 1 >>> def interpreter(prompt='=> '): while 1: command = raw_input(prompt) if command: rval = commands(command) if not rval: break else: break >>> interpreter() => open opening => close not a valid command => duh not a valid command => exit >>> >>> interpreter() # no at all command is another way to quit => >>> If you want to launch such a shell from the operating system, you could stick the above in a module and do so, again without arguments. You could uses the sys.exit(0) thing to terminate Python when done. Again you don't need the argv stuff because it's Python's own raw_input that's reading what the user types in response to =>, not something entered at the DOS or UNIX prompt for which something(s) you'd need to interrogate the system. Note: there's are modules which do a lot of the work for you, if you're wanting to build a shell. shlex and cmd are the two to look at. 'Python 2.1 Bible' (Hungry Minds, 2001) has a whole chapter entitled 'Building Simple Command Interpreters'. This is one of my favorite Python books by the way -- very comprehensive and well-presented IMO. Kirby From urnerk@qwest.net Sat Oct 6 20:49:32 2001 From: urnerk@qwest.net (Kirby Urner) Date: Sat, 06 Oct 2001 12:49:32 -0700 Subject: [Tutor] A command line In-Reply-To: <4.2.0.58.20011006121024.019b0910@pop3.norton.antivirus> References: <3BBE0134.DC8E02BF@stormwall.org> Message-ID: <4.2.0.58.20011006124727.00aa8270@pop3.norton.antivirus> > > >>> def interpreter(prompt='=> '): > while 1: > command = raw_input(prompt) > if command: > rval = commands(command) > if not rval: > break > else: break Sorry about the indentation problem. Here's a slightly modified version: >>> def interpreter(prompt='=> '): while 1: command = raw_input(prompt) if command: if not commands(command) break else: break Kirby From mark21rowe@yahoo.com Sun Oct 7 00:34:22 2001 From: mark21rowe@yahoo.com (Mark Rowe) Date: Sun, 07 Oct 2001 12:34:22 +1300 Subject: [Tutor] A command line References: <3BBE0134.DC8E02BF@stormwall.org> Message-ID: <3BBF94FE.1080900@yahoo.com> Hey Tor, One reason it doesn't work is that the sys.argv list contains strings. In the commands function you are comparing a string (sys.argv[0]) with a builtin method(open). This can be fixed by comparing sys.argv[0] with the string 'open' as shown: def commands(): if sys.argv[0] == 'open': print 'opening' elif sys.argv[1] == 'exit': sys.exit() else: print 'not a valid command' Mark Rowe Tor Stormwall wrote: > Hi! > > I'm trying make a little interpreter that will other run > commands. > > But why cant I do like this: > > import os > import sys > > def commands(): > if sys.argv[0] == open: > print "opening" > elif sys.argv[0] == exit: > sys.exit() > else: > print "not a valid command" > > def interpreter(prompt='=> '): > try: > while 1: > command = raw_input(prompt) > try: > #flag = os.system('echo Hej') > if command: > commands() # calling "def commands()" > except (IndexError, KeyError): > print "'%s' not a valid command" % command > else: > pass > except EOFError: pass > > interpreter() > > > > Best Regards, > Tor Stormwall > _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From âèëëà_@rambler.ru Mon Oct 8 07:12:50 2001 From: âèëëà_@rambler.ru (Villa) Date: Mon, 8 Oct 2001 10:12:50 +0400 Subject: [Tutor] =?windows-1251?Q?=CF=F0=EE=E4=E0=E5=F2=F1=FF_=E2=E8=EB=EB=E0_=ED=E0_=E1=E5=F0=E5=E3=F3_=EE=EA=E5=E0=ED=E0?= Message-ID: <126012001101861250209@rambler.ru> Ïðîäàåòñÿ âèëëà íà Ñåéøåëàõ â 20-òè ìåòðàõ îò Èíäèéñêîãî îêåàíà. 200 êâ.ì. 0,15 Ãà. Ìåáåëü, ñèãíàëèçàöèÿ, ïðèñëóãà. Ëó÷øèé êëèìàò íà Çåìëå (êðóãëûé ãîä òåìï. âîçäóõà è âîäû 28°)! Ìîñêîâñêîå âðåìÿ. Ïðÿìîé áåçâèçîâûé ïåðåëåò Àýðîôëîòîì. Åñëè Âû çàèíòåðåñîâàëèñü ýòèì ïðåäëîæåíèåì è õîòèòå ïîëó÷èòü áîëåå ïîäðîáíóþ èíôîðìàöèþ, ïîøëèòå ïóñòîå ïèñüìî ïî àäðåñó: villa@wwwlettera.com. Ïðè ýòîì â ïîëå "Òåìà" îáÿçàòåëüíî óêàæèòå: "Ïðèøëèòå ïîäðîáíóþ èíôîðìàöèþ". From dyoo@hkn.eecs.berkeley.edu Mon Oct 8 08:45:09 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 8 Oct 2001 00:45:09 -0700 (PDT) Subject: [Tutor] a question (fwd) Message-ID: Dear Gino, You probably meant to send this to "tutor@python.org", not "tutor-admin@python.org." Let me forward this to the rest of the tutors there. Tutor-admin mail directs itself only to the list administrators. About your question: yes, it's about the same. Underneath, there's been some architectural changes on how the regular expression engine works, but not at a level that will make a difference. There's a small mention about this in the "What's New in Python 2.1" documen What other questions on regular expressions do you have? Talk to you later! ---------- Forwarded message ---------- Date: Fri, 5 Oct 2001 11:45:54 -0700 From: Gino Kuo To: tutor-admin@python.org Subject: a question Hi all, I am learning the very basics of regular expression. Most of the materials I read have such messages after compiling the regular expression: . I have Python 2.1. When I compile my expressions, Python gives me a different message:. Do those two messaves have the same meaning? From discuss@sendme.cz Mon Oct 8 09:54:22 2001 From: discuss@sendme.cz (A) Date: Mon, 8 Oct 2001 10:54:22 +0200 Subject: [Tutor] DNS module or how to ... ? Message-ID: <3BC185DE.6490.6E5428@localhost> Hello, Is there a DNS module available for Python ? Or is there a method how I can , from my python program, find out an email server for a particular domain? For example for email printers@sendme.cz I find out that email server mail.contactel.cz serves for domain sendme.cz Thank you for help. Ladislav From printers@sendme.cz Mon Oct 8 09:54:22 2001 From: printers@sendme.cz (A) Date: Mon, 8 Oct 2001 10:54:22 +0200 Subject: [Tutor] DNS module or how to ... ? Message-ID: <3BC185DE.30945.6E5441@localhost> Hello, Is there a DNS module available for Python ? Or is there a method how I can , from my python program, find out an email server for a particular domain? For example for email printers@sendme.cz I find out that email server mail.contactel.cz serves for domain sendme.cz Thank you for help. Ladislav From d_coughlan@altavista.com Mon Oct 8 14:04:07 2001 From: d_coughlan@altavista.com (Damian Coughlan) Date: 8 Oct 2001 06:04:07 -0700 Subject: [Tutor] help Message-ID: <20011008130407.10352.cpmta@c012.sfo.cp.net> This is a multi-part message in MIME format... ------------=_1002546246-9552-0 Content-Type: text/plain Content-Disposition: inline Hi, enquiring about the unittest module. A simple program I have implemented using the testcase class encounters problems with the interpreter saying no module named docviewdoc. Please assist. simple test of instantiating a document # author Damien Coughlan 5/10/01 import unittest from Docviewdoc import DocviewDoc class DocviewDocTestCase(unittest.TestCase): def setup(self): print "setUp called" def tearDown(self): print "tearDown called" def runTest(self): doc=None doc=Docviewedoc() assert doc!=null, 'Coudl not instantiate DocviewDoc' def suite(): testSuite=unittest.TestSuite() testSuite.addTest(DocviewDocTestCase()) return testSuite def main(): runner = unittest.QtTestRunner() runner.run(suite()) if __name__=="__main__": main() Find the best deals on the web at AltaVista Shopping! http://www.shopping.altavista.com ------------=_1002546246-9552-0 Content-Type: application/octet-stream; name="dvt1.py" Content-Disposition: attachment; filename="dvt1.py" Content-Transfer-Encoding: base64 IyBhIHNpbXBsZSB0ZXN0IG9mIGluc3RhbnRpYXRpbmcgYSBkb2N1bWVudA0K IyBhdXRob3IgRGFtaWVuIENvdWdobGFuIDUvMTAvMDENCg0KaW1wb3J0IHVu aXR0ZXN0DQpmcm9tIERvY3ZpZXdkb2MgaW1wb3J0IERvY3ZpZXdEb2MNCg0K Y2xhc3MgRG9jdmlld0RvY1Rlc3RDYXNlKHVuaXR0ZXN0LlRlc3RDYXNlKToN Cg0KICAgIGRlZiBzZXR1cChzZWxmKToNCiAgICAgICAgcHJpbnQgInNldFVw IGNhbGxlZCINCg0KICAgIGRlZiB0ZWFyRG93bihzZWxmKToNCiAgICAgICAg cHJpbnQgInRlYXJEb3duIGNhbGxlZCINCg0KICAgIGRlZiBydW5UZXN0KHNl bGYpOg0KICAgICAgICAgICANCiAgICAgICAgZG9jPU5vbmUNCiAgICAgICAg ZG9jPURvY3ZpZXdlZG9jKCkNCiAgICAgICAgYXNzZXJ0IGRvYyE9bnVsbCwg J0NvdWRsIG5vdCBpbnN0YW50aWF0ZSBEb2N2aWV3RG9jJw0KICAgICAgICAN CmRlZiBzdWl0ZSgpOg0KICAgIHRlc3RTdWl0ZT11bml0dGVzdC5UZXN0U3Vp dGUoKQ0KICAgIHRlc3RTdWl0ZS5hZGRUZXN0KERvY3ZpZXdEb2NUZXN0Q2Fz ZSgpKQ0KICAgIHJldHVybiB0ZXN0U3VpdGUNCg0KZGVmIG1haW4oKToNCiAg ICBydW5uZXIgPSB1bml0dGVzdC5RdFRlc3RSdW5uZXIoKQ0KICAgIHJ1bm5l ci5ydW4oc3VpdGUoKSkNCg0KaWYgX19uYW1lX189PSJfX21haW5fXyI6DQog ICAgbWFpbigpDQo= ------------=_1002546246-9552-0-- From arcege@speakeasy.net Mon Oct 8 14:21:20 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Mon, 8 Oct 2001 09:21:20 -0400 Subject: [Tutor] DNS module or how to ... ? In-Reply-To: <3BC185DE.6490.6E5428@localhost>; from export@bmatrading.com on Mon, Oct 08, 2001 at 10:54:22AM +0200 References: <3BC185DE.6490.6E5428@localhost> Message-ID: <20011008092120.B9038@speakeasy.net> On Mon, Oct 08, 2001 at 10:54:22AM +0200, A wrote: > Is there a DNS module available for Python ? > Or is there a method how I can , from my python program, find out > an email server for a particular domain? You might want to look at the dnslib module in the "Demo" directory (included with the Python source distribution). -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | | Ailment info: http://www.speakeasy.org/~arcege/michaelwatch.html | From dyoo@hkn.eecs.berkeley.edu Mon Oct 8 18:00:30 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 8 Oct 2001 10:00:30 -0700 (PDT) Subject: [Tutor] help In-Reply-To: <20011008130407.10352.cpmta@c012.sfo.cp.net> Message-ID: On 8 Oct 2001, Damian Coughlan wrote: > Hi, enquiring about the unittest module. A simple program I have > implemented using the testcase class encounters problems with the > interpreter saying no module named docviewdoc. Please assist. Can you show us the exact error message? Even seeing the capitalization that Python uses in the error message is useful! *grin* > from Docviewdoc import DocviewDoc What file is Docviewdoc --- is it a Python module that you've written? > doc=Docviewedoc() ^^^^^^^^^^^ There might be a small typo here; can you double check? From Blake.Garretson@dana.com Mon Oct 8 18:13:29 2001 From: Blake.Garretson@dana.com (Blake.Garretson@dana.com) Date: Mon, 8 Oct 2001 13:13:29 -0400 Subject: [Tutor] converting decimals to fractions Message-ID: This is less of a Python question than it is an algorithm question, but it should still apply since Python has some cool data structures available to apply to the solution. I have a script that does some length calculations and prints out results in decimal inches. (e.g. 1.537", 4.230", etc.) Converting these to fractions of an inch is simple enough (e.g. 1+537/1000, 4+23/100, etc.), but suppose I only want answers in the standard fractions of an inch (i.e. fourths of and inch, thirty-seconds of an inch, etc.). I'm looking for suggestions on implementation. My approach is to use a lookup table, probably in dictionary form. The table will contain "bins" of fractions in increments of 1/32 with upper and lower limits for the decimal equivlent. The limits would be calculated by adding and subtracting 1/64 to the base number. For instance, a given decimal would be determined to be 3/32 if the decimal equivalent was between 0.09375+0.015625 and 0.09375-0.015625. The program could create the lookup table right at the beginning, and the table would hold all of these upper and lower limits along with their corresponding fraction. The fraction itself (in string form) would probably be the dictionary key. To convert a decimal, I would just use a loop to compare the number to each set of limits. Does anyone have a better method for this? Thanks, Blake Garretson From tim.one@home.com Mon Oct 8 18:47:53 2001 From: tim.one@home.com (Tim Peters) Date: Mon, 8 Oct 2001 13:47:53 -0400 Subject: [Tutor] converting decimals to fractions In-Reply-To: Message-ID: [Blake.Garretson@dana.com] > This is less of a Python question than it is an algorithm question, but > it should still apply since Python has some cool data structures > available to apply to the solution. In this case, I think some simple arithmetic will suffice. > I have a script that does some length calculations and prints out results > in decimal inches. (e.g. 1.537", 4.230", etc.) Converting these to > fractions of an inch is simple enough (e.g. 1+537/1000, 4+23/100, etc.), > but suppose I only want answers in the standard fractions of an inch > (i.e. fourths of and inch, thirty-seconds of an inch, etc.). The "etc" is important: how far down do you want to go? That is, is 1/32 the smallest granularity you care about? BTW, in my college days, I applied for a job on the Harley-Davidson assembly line. I barely made it: during the interview, the foreman looked me in the eyes and demanded "how many sixty-fourths of an inch are in an inch?". It seemed like *such* a stupid question, I asked him to repeat it. He did. Then it seemed like it must be a trick question, and my mind raced futilely looking for "the trick". After about a minute, he lost patience and asked for my answer. Hesitant and defeated, I weakly asked "umm, 64?". "Right!" he beamed, "Now let's see if you can read a micrometer.". def tofrac(x, largest_denominator=32): """Return triple (i, j, k) where x ~= i + j/k. x >= 0 is required. i, j and k are integers >= 0, and k is > 0. j and k have no factors in common, unless j is 0. Optional argument largest_denominator (default 32) should be a power of 2, and is the largest value k can have. """ if not x >= 0: raise ValueError("x must be >= 0") scaled = int(round(x * largest_denominator)) whole, leftover = divmod(scaled, largest_denominator) if leftover: while leftover % 2 == 0: leftover >>= 1 largest_denominator >>= 1 return whole, leftover, largest_denominator format = "%d %d/%d" print format % tofrac(1.537) print format % tofrac(4.230) print format % tofrac(4.230, 128) print format % tofrac(4.240) print format % tofrac(8) That prints 1 17/32 4 7/32 4 29/128 4 1/4 8 0/32 > I'm looking for suggestions on implementation. My approach is to use a > lookup table, probably in dictionary form. The table will contain "bins" > of fractions in increments of 1/32 with upper and lower limits for the > decimal equivlent. The limits would be calculated by adding and > subtracting 1/64 to the base number. For instance, a given decimal > would be determined to be 3/32 if the decimal equivalent was between > 0.09375+0.015625 and 0.09375-0.015625. The code above gets the same effect, pretty much by answering the question "How many 32nds of an inch are in an inch?" : multiply by 32, round to an int, then take the quotient and remainder from dividing by 32. From Blake.Garretson@dana.com Mon Oct 8 19:37:12 2001 From: Blake.Garretson@dana.com (Blake.Garretson@dana.com) Date: Mon, 8 Oct 2001 14:37:12 -0400 Subject: [Tutor] converting decimals to fractions Message-ID: Thanks, Tim! I have an uncanny knack for finding a brute force method even if there is a more obvious and very elegant solution available. Thanks for the great code. Blake Garretson "Tim Peters" , .com> cc: Subject: RE: [Tutor] converting decimals to fractions 10/08/2001 01:47 PM >def tofrac(x, largest_denominator=32): > """Return triple (i, j, k) where x ~= i + j/k. > > x >= 0 is required. > i, j and k are integers >= 0, and k is > 0. > j and k have no factors in common, unless j is 0. > > Optional argument largest_denominator (default 32) should be a > power of 2, and is the largest value k can have. > """ > > if not x >= 0: > raise ValueError("x must be >= 0") > scaled = int(round(x * largest_denominator)) > whole, leftover = divmod(scaled, largest_denominator) > if leftover: > while leftover % 2 == 0: > leftover >>= 1 > largest_denominator >>= 1 > return whole, leftover, largest_denominator From jeff@ccvcorp.com Mon Oct 8 20:08:37 2001 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon, 08 Oct 2001 12:08:37 -0700 Subject: [Tutor] ?4uplz-> function Message-ID: <3BC1F9B5.5161D85B@ccvcorp.com> >From: "David Meltzer" >Date: Fri, 5 Oct 2001 17:04:27 -0400 >Subject: [Tutor] ?4uplz-> function > >hilo2u and thanks for reading this, >i would like to find a way to create a def that behaves more like a builtin >keyword such as 'print' in that i would not need to use a parenthesis. > >...... > >so perhaps you know a way to make the illegal legal No, this can't be done. There's a *reason* that it's illegal. Much of that reason, is that it is almost always a really bad idea. Among other things, it makes it very ambiguous as to what is intended as a parameter to the statement/function, and what isn't. Especially if you've got a complex expression, say, printit var1 func var2 var3 Even if we know that both printit and func are statement/functions, we can't tell how this should be parsed--it could be any of the following: printit(var1, func(var2, var3)) printit(var1, func(var2), var3) printit(var1, func(), var2, var3) printit(var1, func(var2)), var3 printit(var1, func(), var2), var3 printit(var1, func()), var2, var3 printit(var1), func(var2, var3) .... printit(), var1, func(), var2, var3 .... And so on and so on. How does the python parser know which you mean?? And more importantly, how does someone reading your code know which you mean? Especially since there may be variable numbers of arguments... And really... what would it be saving you?? How difficult is it to add a couple more parens?? (This sometimes-use-parens-but-sometimes-don't mess is one of the things that I hate *most* about Visual Basic--I would be mortified to see the same mistake work its way into Python.) Jeff Shannon Technician/Programmer Credit International From urnerk@qwest.net Mon Oct 8 20:13:34 2001 From: urnerk@qwest.net (Kirby Urner) Date: Mon, 08 Oct 2001 12:13:34 -0700 Subject: [Tutor] converting decimals to fractions In-Reply-To: Message-ID: <4.2.0.58.20011008120211.00c3e7d0@pop3.norton.antivirus> Probably easier to calculate on the fly, vs. do a lookup table. One algorithm is: take the decimal part of n and convert it to the nearest x/32. Then reduce x/32 to lowest terms by dividing x, 32 by their gcd (greatest common divisor). def div32(n): "x for closest x/32" return round((n-int(n))*1000/32.) def gcd(a,b): "Euclidean Algorithm (recursive form)" if b==0: return a else: return gcd(b,a%b) def mkinch(n): numer = div32(n) thegcd = gcd(numer,32) return "%s %s/%s" % \ (int(n),int(numer/thegcd),int(32/thegcd)) >>> mkinch(1.133) '1 1/8' >>> mkinch(1.185) '1 3/16' >>> mkinch(1.1) '1 3/32' Since writing this, I've seen Tim's. His is no doubt faster, as it takes advantage of the base 2 aspect of your problem thru bit shifting. Kirby From dyoo@hkn.eecs.berkeley.edu Tue Oct 9 07:06:46 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 8 Oct 2001 23:06:46 -0700 (PDT) Subject: SV: SV: [Tutor] Stuck with classes - events [Callbacks / Function calling] In-Reply-To: Message-ID: On Fri, 5 Oct 2001, Danny Kohn wrote: > | Fran: tutor-admin@python.org [mailto:tutor-admin@python.org]For Sean > | 'Shaleh' Perry > | Skickat: den 5 oktober 2001 16:46 > | Till: Danny Kohn > | Kopia: Python Tutor mailing list > > | Consider this. When item A gets a Ctrl+Left click it tells its > | parent to make it the current object. > > And how is this "telling" done in practice in oop? I am very new to > this. I can't say that this is how wxPython does things, but in Tkinter, the GUI "tells" us when things happen by calling some function. I'm more familiar with Tkinter, so I'll use it for the examples here; I'm sure that wxPython uses similar concepts. Here's a small program that responds to pressing a Button: ### from Tkinter import * def sayHello(): print "Hello world!" if __name__ == '__main__': root = Tk() button = Button(root, text="Press me", command=sayHello) button.pack() mainloop() ### This program might initially seem unusual: where are we calling sayHello? And why is it an argument to our button? We're not calling sayHello, since we haven't put parens at the end, so something different must be going on. What is sayHello without parens? ### >>> sayHello ### So we're passing a function, as if it were some piece of data! The statement: button = Button(root, text="Press me", command=sayHello) could be read like this: """Ok, we'll make an instance of this Button. Remember that you belong to this root container, and that you have to display 'Press me'. Oh, and one more thing: if we ever really do press you, we want you to call back THIS function called 'sayHello'. Don't call 'sayHello' now, but just keep this in mind for future reference.""" This style of programming is called event-based programming, and it's all based on the idea of "callbacks". A callback is just a fancy name for a function. Event-based programming is a little weird because we're not in "control" most of the time: some external thing, like the GUI, manages things. However, this manager is able to pass control back to us at key moments, by calling our functions. And that's where control passes back to us. We can "pass control" to an instance if we call that instance's methods. For example: ### class A: def respond(self): print "I'm in A." class B: def __init__(self, friend): self.friend = friend def respond(self): print "I'm in B." print "%s, now you talk!" % self.friend print "But what am I calling? %s" % self.friend.respond self.friend.respond() print "I'm back in B." ### Let's take a look: ### >>> a = A() >>> b = B(a) >>> a.respond() I'm in A. >>> b.respond() I'm in B. <__main__.A instance at 0x81d53d4>, now you talk! But what am I calling? I'm in A. I'm back in B. ### Function calling is the key to all of this; as soon as you see it, it'll hit like a blinding flash of "Eureka!" Another part of the Eureka thing is that you'll eventually see that methods are just functions (with a little dressing to make them spicy.) Play around with it, and keep asking questions, and we'll do what we can to accelerate the Bathtub moment. By the way, I did a search on the web, and found a pretty nice overview on how to do GUI programming here: http://www.wag.caltech.edu/home/rpm/python_course/Lecture_6.pdf It's Tkinter based, but I think it'll still be useful for you. Good luck! From dyoo@hkn.eecs.berkeley.edu Tue Oct 9 07:31:21 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 8 Oct 2001 23:31:21 -0700 (PDT) Subject: [Tutor] ?4uplz-> function In-Reply-To: Message-ID: On Fri, 5 Oct 2001, David Meltzer wrote: > i would like to find a way to create a def that behaves more like a > builtin keyword such as 'print' in that i would not need to use a > parenthesis. > > here is an example > > print 10 //this is legal > > def printit(Num): > print Num > > printit (10) //legal > printit 10 //illegal. > > so perhaps you know a way to make the illegal legal No; in Python, that sort of syntax is reserved only for the builtins. I think the decision to force us to use parentheses on function calls is to simplify the rules: if there's just one way to interpret something, there's less room for misinterpretation. Others have given some examples of where misinterpretation might occur. Even if we somehow cook up a set of rules rules so that Python doesn't get confused, many of us certainly would! *grin* I think it's a deliberate design decision to make parens mandatory for function calls. Because of this single rule, other parts of the Python language are easier to explain. For example: we can easily say that, in Python, parens are the magic symbols we use to make functions fire off, and that without them, functions stay dormant as data that can be passed off to other functions: ### >>> def printit(num): print num ... >>> printit ## What happens if we forget the ## parens? Ah. It's a function. >>> def playItAgain(sam): ... sam(1) ... sam(1) ... >>> playItAgain(printit) 1 1 ### With your proposal, we'd have to interpret: ### >>> printit ### as calling printit with no arguments. But then, how do we pass functions off to other functions? Then we'd have to invent something like a referencing operator, and then Python suddenly wouldn't be as nice to work with. Lots of implications from a "simple" syntax change. I'm glad I'm not a language designer. *grin* Hope this helps! From dyoo@hkn.eecs.berkeley.edu Tue Oct 9 07:51:59 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 8 Oct 2001 23:51:59 -0700 (PDT) Subject: [Tutor] help ['import' failing?] In-Reply-To: <20011008172324.28610.cpmta@c012.sfo.cp.net> Message-ID: On 8 Oct 2001, Damian Coughlan wrote: > not to go over covered ground but the docviewdoc is in > lowercase and is not the module Docviewdoc as shown in line 5 > statement saying > from docviewdoc import Docviewdoc Is docviewdoc.py something that you've written, or is a package that someone else has written? Also, is the file literally 'docviewdoc.py', or is there some capitalization in the file name? Computers today are designed to be fussy, so this detail might matter, silly as it is. You may want to check to see if 'docviewdoc.py' is in the same directory as the rest of your program. If not, then it becomes difficult for Python to figure out where to look for docviewdoc. It'll hunt in directories listed in an environment variable called "PYTHONPATH", but then, it'll give up, since hunting through hard drive can get expensive. Let's find where docviewdoc.py is actually located on your computer first. Can you show where it's located on your computer? By the way, make sure to reply to "tutor@python.org", and not just to me. I'm typing this from my laptop, and the small keys make it a little difficult to type accurately. I'm often hoping that someone else answers your question well so you don't have to put up with my misspellings. *grin* By emailing the whole list, we do a little bit of load-balancing among all the tutors, as well as new people who'd like to learn from the questions asked. Good luck to you. From Chris Nally" This is a multi-part message in MIME format. ------=_NextPart_000_0007_01C15095.A6FF8F80 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I am learning to program, I have chosen Python as my first language = to learn. My question is, I have written some command line programs = (small programs) and I would like to run them on a different computer. = How can I do this without installing Python on the second computer? = Basically how do you package programs to run on other computers as = "software" without actually installing Python to run them? For = instance, if I wrote a Python program with Tkinter how would that = program be packaged to be installed and run on a computer? Thanks, Chris Nally Louisville, Kentucky ------=_NextPart_000_0007_01C15095.A6FF8F80 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
    I am learning to program, I have = chosen=20 Python as my first language to learn.  My question is, I have = written some=20 command line programs (small programs) and I would like to run them on a = different computer.  How can I do this without installing Python on = the=20 second computer?  Basically how do you package programs to run on = other=20 computers as "software" without actually installing Python to run = them? =20 For instance, if I wrote a Python program with Tkinter how would that = program be=20 packaged to be installed and run on a computer?
 
Thanks,
 
Chris Nally
Louisville, Kentucky
------=_NextPart_000_0007_01C15095.A6FF8F80-- From ak@silmarill.org Tue Oct 9 12:47:25 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Tue, 09 Oct 2001 07:47:25 -0400 Subject: [Tutor] running programs In-Reply-To: <000a01c150b7$306be860$0101a8c0@chris> References: <000a01c150b7$306be860$0101a8c0@chris> Message-ID: <20011009074725.A5824@sill.silmarill.org> On Tue, Oct 09, 2001 at 07:40:22AM -0400, Chris Nally wrote: > I am learning to program, I have chosen Python as my first language to learn. My question is, I have written some command line programs (small programs) and I would like to run them on a different computer. How can I do this without installing Python on the second computer? Basically how do you package programs to run on other computers as "software" without actually installing Python to run them? For instance, if I wrote a Python program with Tkinter how would that program be packaged to be installed and run on a computer? > > Thanks, > > Chris Nally > Louisville, Kentucky There's py2exe and something else of that sort but really, the easiest and most common option is to simply install python on that computer. If you want to save hd space, forget it: python is small and in py2exe and such it's simply packaged up into an executable - you don't save any space anyway. - Andrei -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From jerryl@europa.com Tue Oct 9 18:10:26 2001 From: jerryl@europa.com (Jerry Lake) Date: Tue, 9 Oct 2001 10:10:26 -0700 Subject: [Tutor] unexpected error In-Reply-To: <20011009074725.A5824@sill.silmarill.org> Message-ID: <000001c150e5$4ab085e0$0103670a@europa.com> I'm reading through the eBook "how to think like a computer programmer" python version and I'm following along in chapter 7.9 "The string Module" however I get this error from this code, any ideas ? the output is completely not expected #!/usr/bin/python2 import string fruit = "banana" count = 0 index = 0 for char in fruit: if char == 'a': count = count + 1 print count indeX = string.find(fruit, "a") print indeX this is a 14 1 3 Traceback (most recent call last): File "./fortest.py", line 13, in ? indeX = string.find(fruit, "a") AttributeError: 'string' module has no attribute 'find' Jerry Lake Interface Engineering Technician From gbcs1978@hotmail.com Tue Oct 9 19:07:23 2001 From: gbcs1978@hotmail.com (Glauco Silva) Date: Tue, 9 Oct 2001 15:07:23 -0300 Subject: [Tutor] Help Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0100_01C150D4.19DA24A0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi , I would like to know how i can to do one Scrollbar to be linked with = two Listbox if it's possible . Thank you Glauco ------=_NextPart_000_0100_01C150D4.19DA24A0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi ,
I would like to know how i can to do = one Scrollbar=20 to be linked with two Listbox if it's possible .
Thank you
Glauco
------=_NextPart_000_0100_01C150D4.19DA24A0-- From dyoo@hkn.eecs.berkeley.edu Tue Oct 9 19:06:50 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 9 Oct 2001 11:06:50 -0700 (PDT) Subject: [Tutor] unexpected error In-Reply-To: <000001c150e5$4ab085e0$0103670a@europa.com> Message-ID: On Tue, 9 Oct 2001, Jerry Lake wrote: > I'm reading through the eBook > "how to think like a computer programmer" python version > and I'm following along in chapter 7.9 "The string Module" > > however I get this error from this code, any ideas ? the output is > completely not expected > > > #!/usr/bin/python2 > > import string > > fruit = "banana" > count = 0 > index = 0 > for char in fruit: > if char == 'a': > count = count + 1 > print count > > indeX = string.find(fruit, "a") > print indeX > > > > this is a > 14 > 1 > 3 > Traceback (most recent call last): > File "./fortest.py", line 13, in ? > indeX = string.find(fruit, "a") > AttributeError: 'string' module has no attribute 'find' ??! Weird! Let's check one thing. Can you put: ### print string.__file__ ### right after you import the string module? This will show us where Python is finding the string module. My best guess so far is that you might have a 'string.py' file in your current directory, which is obscuring the standard library's string module. Here's what happens on my side when I run your snippet: ### 3 1 ### Hope this helps! From jerryl@europa.com Tue Oct 9 19:18:54 2001 From: jerryl@europa.com (Jerry Lake) Date: Tue, 9 Oct 2001 11:18:54 -0700 Subject: [Tutor] unexpected error In-Reply-To: Message-ID: <000101c150ee$db3e0d40$0103670a@europa.com> you are correct, that is what it was I guess I will have to learn a few more modules, so I don't do that Thanks, Jerry Lake Interface Engineering Technician From pobrien@orbtech.com Tue Oct 9 19:29:26 2001 From: pobrien@orbtech.com (Patrick K. O'Brien) Date: Tue, 9 Oct 2001 13:29:26 -0500 Subject: [Tutor] unexpected error In-Reply-To: Message-ID: I'm biased, of course, but I think these kinds of situations are much easier to understand and investigate in the PyCrust shell. All objects in the current namespace can be drilled through in the PyCrust namespace tree control (called PyFilling). If the object is a module, class or method, PyFilling even displays the source code for the object. I've spent the past couple of days poking around Zope and ZODB using PyCrust and it has been a great learning experience. Just a suggestion. http://sourceforge.net/projects/pycrust/ --- Patrick K. O'Brien Orbtech (http://www.orbtech.com) "I am, therefore I think." -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of Danny Yoo Sent: Tuesday, October 09, 2001 1:07 PM To: Jerry Lake Cc: tutor@python.org Subject: Re: [Tutor] unexpected error On Tue, 9 Oct 2001, Jerry Lake wrote: > I'm reading through the eBook > "how to think like a computer programmer" python version > and I'm following along in chapter 7.9 "The string Module" > > however I get this error from this code, any ideas ? the output is > completely not expected > > > #!/usr/bin/python2 > > import string > > fruit = "banana" > count = 0 > index = 0 > for char in fruit: > if char == 'a': > count = count + 1 > print count > > indeX = string.find(fruit, "a") > print indeX > > > > this is a > 14 > 1 > 3 > Traceback (most recent call last): > File "./fortest.py", line 13, in ? > indeX = string.find(fruit, "a") > AttributeError: 'string' module has no attribute 'find' ??! Weird! Let's check one thing. Can you put: ### print string.__file__ ### right after you import the string module? This will show us where Python is finding the string module. My best guess so far is that you might have a 'string.py' file in your current directory, which is obscuring the standard library's string module. Here's what happens on my side when I run your snippet: ### 3 1 ### Hope this helps! _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From urnerk@qwest.net Tue Oct 9 23:54:49 2001 From: urnerk@qwest.net (Kirby Urner) Date: Tue, 09 Oct 2001 15:54:49 -0700 Subject: [Tutor] set/getattr and inheritance In-Reply-To: <4.2.0.58.20011006111909.019bcf00@pop3.norton.antivirus> References: <4.2.0.58.20011005134556.01a769a0@pop3.norton.antivirus> <200110051900.OAA08548@bilbo.bio.purdue.edu> Message-ID: <4.2.0.58.20011009154619.00c4b830@pop3.norton.antivirus> I finally got that __getattribute__ provides behavior similar to __getattr__, except it's *always* called, whether or not the attribute is already in self.__dict__. >>> class C(object): def __init__(self,value): self.value = value def __getattribute__(self,arg): return "Value: %s" % object.__getattribute__(self,arg) >>> o = C(3) >>> o.value 'Value: 3' The automatic triggering is implemented in the new universal object, so you need to subclass object if you want this behavior (otherwise __getattribute__ will just sit there like an inert lump, not triggered by anything except an explicit call). Also, you don't want to invoke return self.__dict__[arg] to return the attribute as part of the function'd definition, as this just reinvokes __getattribute__ again in an endlessly recursive tailspin. Rather, call the base class version of __getattribute__, as shown above. This is all new with 2.2a4 -- becoming part of standard Python of the future, but not currently accessible to users of any final release. I finally learned about this behavior from Guido's PowerPoint slides available to PowerPointers at: http://zpug.org/dc/ (from a presentation on Sept 26). Kirby From dyoo@hkn.eecs.berkeley.edu Wed Oct 10 05:12:44 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 9 Oct 2001 21:12:44 -0700 (PDT) Subject: [Tutor] unexpected error In-Reply-To: <000101c150ee$db3e0d40$0103670a@europa.com> Message-ID: On Tue, 9 Oct 2001, Jerry Lake wrote: > you are correct, that is what it was I guess I will have to learn a > few more modules, so I don't do that Glad to be of help. Don't worry; I've done something like that a few times myself... *grin* From alan.gauld@bt.com Wed Oct 10 10:22:40 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 10 Oct 2001 10:22:40 +0100 Subject: [Tutor] converting decimals to fractions Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFCF@mbtlipnt02.btlabs.bt.co.uk> Hi Blake, Two points to make: 1) Your method will work. 2) Its not the most efficient way to use a dictionary. Given (2), another approach which might(I haven't tested this!) be more efficient is to extract the fractional part, round to the required precision - looks like 6 digits then do a binary chop search on a list of tuples. The indexing/sequential access of the list might in this case be better than searching the values of a dictionary. (Wth 64 entries your *worst* case should be 6 tests...) The tuples would of course contain the fraction string and the equivalent number equivalent. As ever with floats beware of rounding errors. Just some thoughts. Alan G. From alan.gauld@bt.com Wed Oct 10 10:39:04 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 10 Oct 2001 10:39:04 +0100 Subject: [Tutor] running programs Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFD0@mbtlipnt02.btlabs.bt.co.uk> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C1516F.66A343C0 Content-Type: text/plain; charset="iso-8859-1" I am learning to program, I have chosen Python as my first language to learn. My question is, I have written some command line programs (small programs) and I would like to run them on a different computer. Well done, thats the hardest bit over :-) How can I do this without installing Python on the second computer? There are a few packages around that can do this. py2exe seems to be the favourite but Gordon McMillan also has an installer program on the ActiveState site somewhere. However first to clear up some common misconceptions: Basically how do you package programs to run on other computers as "software" without actually installing Python to run them? You can't. All the above solutions do is pack up the smallest bit of python needed to run your program and combine it with your program as a single unit. This is true of every program even C++ ones. If you delete the MFC DLL on your windows PC you will find that virtually nothing works! Similarly on Unix if you delete the libc files nothing will work. This is because every program is built to use a standard runtime environment, its just that some of these environments are installed by default on the operating system while others - like Python - must be installed later. For instance, if I wrote a Python program with Tkinter how would that program be packaged to be installed and run on a computer? Thanks, Chris Nally Louisville, Kentucky ------_=_NextPart_001_01C1516F.66A343C0 Content-Type: text/html; charset="iso-8859-1"
    I am learning to program, I have chosen Python as my first language to learn.  My question is, I have written some command line programs (small programs) and I would like to run them on a different computer.   
Well done, thats the hardest bit over :-)
 
 How can I do this without installing Python on the second computer?   
 
There are a few packages around that can do this.
py2exe seems to be the favourite but Gordon McMillan
also has an installer program on the ActiveState
site somewhere.
 
However first to clear up some common misconceptions:
 
 Basically how do you package programs to run on other computers as "software" without actually installing Python to run them?   
 
You can't. All the above solutions do is pack up the smallest bit of python needed to run your program and combine it with your program as a single unit.
 
This is true of every program even C++ ones.
If you delete the MFC DLL on your windows PC you will
find that virtually nothing works! Similarly on Unix
if you delete the libc files nothing will work. This
is because every program is built to use a standard
runtime environment, its just that some of these
environments are installed by default on the operating system while others - like Python - must be installed later.
 
 
 For instance, if I wrote a Python program with Tkinter how would that program be packaged to be installed and run on a computer?
 
Thanks,
 
Chris Nally
Louisville, Kentucky
------_=_NextPart_001_01C1516F.66A343C0-- From alan.gauld@bt.com Wed Oct 10 10:45:07 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 10 Oct 2001 10:45:07 +0100 Subject: [Tutor] running programs Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFD1@mbtlipnt02.btlabs.bt.co.uk> > most common option is to simply install python on that > computer. If you want to save hd space, forget it: > python is small and in py2exe and such > it's simply packaged up into an executable - you don't > save any space anyway. For a single program that's not quite true since the installers only install the barest bits of python needed. (NO docs and only a few libs/modules) But if you install several such programs you will conversely wind up taking more space than if you just installed Python because you get the same core elements installed multiple times!! Finally, as I was going to add in my last message just before Oulooks send key caught me out... You can always combine the Python installer with your program as a kind of super set installer. In fact some of the fancier installer software would allow you to check the registry to see if Python was already there and adapt as necessary. Alan g From blakew@sonainnovations.com Wed Oct 10 14:23:35 2001 From: blakew@sonainnovations.com (Blake Winton) Date: Wed, 10 Oct 2001 09:23:35 -0400 Subject: [Tutor] help ['import' failing?] References: Message-ID: <005e01c1518e$c418a580$d6d35fd8@quintessential> Danny Yoo wrote: > > from docviewdoc import Docviewdoc Searching for this line on Google gives a link to a subpage of: http://stage.linuxports.com/pyqt/book1.htm Which is what I followed to get an understanding of what's going on. > Is docviewdoc.py something that you've written, or is a package that > someone else has written? It's a file they have created earlier in the tutorial. It seems like he's jumped into the middle of the tutorial, and doesn't have the files from the earlier sections. To make things worse, there doesn't seem to be a zip file of all the code. In a private conversation, Danny mentioned that perhaps someone on the tutor list has worked their way through that tutorial, and might have the code already typed out... So I'm posting this to the tutors, and asking if anyone has the code. Thanks, Blake. From dyoo@hkn.eecs.berkeley.edu Wed Oct 10 19:12:34 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 10 Oct 2001 11:12:34 -0700 (PDT) Subject: [Tutor] Help In-Reply-To: Message-ID: On Tue, 9 Oct 2001, Glauco Silva wrote: > I would like to know how i can to do one Scrollbar to be linked with > two Listbox if it's possible . Thank you Glauco According to the documentation on the Scrollbar widget: http://www.pythonware.com/library/tkinter/introduction/scrollbar.htm we can connect a Scrollbar to a single listbox by configuring it. If we look at their example at: http://www.pythonware.com/library/tkinter/introduction/x7583-patterns.htm scrollbar.config(command=listbox.yview) A scrollbar interacts with its environment by calling back the "command" function whenever we fiddle with the scrollbar. At first glance, it looks like a scrollbar can only be connected to one callback, so that appears to limit us to one widget. However, nothing stops us from having that callback do something to two things! Here's a small utility class I cooked up to make this easier: it's a callback-maker that ties two preexisting callbacks together in one bundle: ### class TieTwoCallbacks: def __init__(self, callback1, callback2): self.callback1, self.callback2 = callback1, callback2 def __call__(self, *args): apply(self.callback1, args) apply(self.callback2, args) ### To get a feel for what this is doing, here's a small sample run with some non-GUI elements: ### >>> def greeting(name): print "hello", name ... >>> def farewell(name): print "goodbye", name ... >>> a_chance_meeting = TieTwoCallbacks(greeting, farewell) >>> a_chance_meeting('glauco silva') hello glauco silva goodbye glauco silva ### With this, we can imagine configuring your scrollbar like this: ### composite_callback = TieTwoCallbacks(listbox1.yview, listbox2.yview) scrollbar.config(command=composite_callback) ### so that when we move the scrollbar, that scrollbar will call our composite_callback. And since the composite_scrollback knows about listbox1.yview and listbox2.yview, it can yell at both of them. We can have even more fun: once we have something that ties together two things, we can tie together multiple things! ### >>> def handshake(dont_care): print "Let's shake!" ... >>> another_chance_meeting = TieTwoCallbacks(greeting, ... TieTwoCallbacks(handshake, farewell)) >>> another_chance_meeting('guido') hello guido Let's shake! goodbye guido ### However, this is completely untested code --- I haven't seen how this will work with listboxes. *grin* If you have questions about the code above, please feel free to ask. From james2dope@yahoo.com Wed Oct 10 21:32:42 2001 From: james2dope@yahoo.com (james middendorff) Date: Wed, 10 Oct 2001 13:32:42 -0700 (PDT) Subject: [Tutor] help Message-ID: <20011010203242.81598.qmail@web13906.mail.yahoo.com> --0-476770287-1002745962=:79170 Content-Type: text/plain; charset=us-ascii I have been trying to get this to work but everytime I run it and type quit, it prints what I want it to but it also prints my error message as well? this is my code so far can someone explain what I am doing wrong thanks! import os, sys try: filename = raw_input("whats the file?('quit' to quit)") if filename == 'quit': print "goodbye" sys.exit() inp = open(filename, "rw") for line in inp.readlines(): print line inp.close() except: IOError print "Error: there is no file there!" "I would kill everyone in this room for a drop of sweet beer." ----Homer Simpson---- --------------------------------- Do You Yahoo!? Make a great connection at Yahoo! Personals. --0-476770287-1002745962=:79170 Content-Type: text/html; charset=us-ascii

I have been trying to get this to work but everytime I run it and type quit, it prints what I want it to but it also prints my error message as well? this is my code so far can someone explain what I am doing wrong thanks!

import os, sys
try:
    filename = raw_input("whats the file?('quit' to quit)")
    if filename == 'quit':
        print "goodbye"
        sys.exit()
    inp = open(filename, "rw")
    for line in inp.readlines():
        print line
    inp.close()      
       
except:
    IOError
    print "Error: there is no file there!"



"I would kill everyone in this room
for a drop of sweet beer."
----Homer Simpson----



Do You Yahoo!?
Make a great connection at Yahoo! Personals. --0-476770287-1002745962=:79170-- From ignacio@openservices.net Wed Oct 10 21:47:01 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Wed, 10 Oct 2001 16:47:01 -0400 (EDT) Subject: [Tutor] help In-Reply-To: <20011010203242.81598.qmail@web13906.mail.yahoo.com> Message-ID: On Wed, 10 Oct 2001, james middendorff wrote: > I have been trying to get this to work but everytime I run it and type quit, it prints what I want it to but it also prints my error message as well? this is my code so far can someone explain what I am doing wrong thanks! > > import os, sys > try: > filename = raw_input("whats the file?('quit' to quit)") > if filename == 'quit': > print "goodbye" > sys.exit() > inp = open(filename, "rw") > for line in inp.readlines(): > print line > inp.close() > > except: > IOError > print "Error: there is no file there!" That's because sys.exit() raises SystemExit. Use 'except IOError:' to focus your exception handling. While you're at it, get rid of the loose 'IOError' in your exception handler. -- Ignacio Vazquez-Abrams From james2dope@yahoo.com Thu Oct 11 00:05:26 2001 From: james2dope@yahoo.com (james middendorff) Date: Wed, 10 Oct 2001 16:05:26 -0700 (PDT) Subject: [Tutor] help Message-ID: <20011010230526.49352.qmail@web13908.mail.yahoo.com> --0-667536255-1002755126=:49331 Content-Type: text/plain; charset=us-ascii I have fixed my last post but I do have a question, I would like to keep looping this over and over until you type quit,thanks for the help! import os, sys try: while 1: filename = raw_input("whats the file?('quit' to quit)") if filename == 'quit': sys.exit() inp = open(filename, "r") for line in inp.readlines(): print line inp.close() except IOError: print "Error: there is no file there!" "I would kill everyone in this room for a drop of sweet beer." ----Homer Simpson---- --------------------------------- Do You Yahoo!? Make a great connection at Yahoo! Personals. --0-667536255-1002755126=:49331 Content-Type: text/html; charset=us-ascii

I have fixed my last post but I do have a question, I would like to keep looping this over and over until you type quit,thanks for the help!

import os, sys
try:
    while 1:
        filename = raw_input("whats the file?('quit' to quit)")
        if filename == 'quit':
            sys.exit()
          
        inp = open(filename, "r")
        for line in inp.readlines():
            print line
        inp.close()      
       
except IOError:
    print "Error: there is no file there!"



"I would kill everyone in this room
for a drop of sweet beer."
----Homer Simpson----



Do You Yahoo!?
Make a great connection at Yahoo! Personals. --0-667536255-1002755126=:49331-- From james2dope@yahoo.com Thu Oct 11 00:05:31 2001 From: james2dope@yahoo.com (james middendorff) Date: Wed, 10 Oct 2001 16:05:31 -0700 (PDT) Subject: [Tutor] help Message-ID: <20011010230531.12021.qmail@web13906.mail.yahoo.com> --0-1370392546-1002755131=:9199 Content-Type: text/plain; charset=us-ascii I have fixed my last post but I do have a question, I would like to keep looping this over and over until you type quit,thanks for the help! import os, sys try: while 1: filename = raw_input("whats the file?('quit' to quit)") if filename == 'quit': sys.exit() inp = open(filename, "r") for line in inp.readlines(): print line inp.close() except IOError: print "Error: there is no file there!" "I would kill everyone in this room for a drop of sweet beer." ----Homer Simpson---- --------------------------------- Do You Yahoo!? Make a great connection at Yahoo! Personals. --0-1370392546-1002755131=:9199 Content-Type: text/html; charset=us-ascii

I have fixed my last post but I do have a question, I would like to keep looping this over and over until you type quit,thanks for the help!

import os, sys
try:
    while 1:
        filename = raw_input("whats the file?('quit' to quit)")
        if filename == 'quit':
            sys.exit()
          
        inp = open(filename, "r")
        for line in inp.readlines():
            print line
        inp.close()      
       
except IOError:
    print "Error: there is no file there!"



"I would kill everyone in this room
for a drop of sweet beer."
----Homer Simpson----



Do You Yahoo!?
Make a great connection at Yahoo! Personals. --0-1370392546-1002755131=:9199-- From ignacio@openservices.net Thu Oct 11 00:10:47 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Wed, 10 Oct 2001 19:10:47 -0400 (EDT) Subject: [Tutor] help In-Reply-To: <20011010230531.12021.qmail@web13906.mail.yahoo.com> Message-ID: On Wed, 10 Oct 2001, james middendorff wrote: > > I have fixed my last post but I do have a question, I would like to keep looping this over and over until you type quit,thanks for the help! > > import os, sys > try: > while 1: > filename = raw_input("whats the file?('quit' to quit)") > if filename == 'quit': > sys.exit() > > inp = open(filename, "r") > for line in inp.readlines(): > print line > inp.close() > > except IOError: > print "Error: there is no file there!" Put the try/except inside the while. -- Ignacio Vazquez-Abrams From urnerk@qwest.net Thu Oct 11 04:45:39 2001 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 10 Oct 2001 20:45:39 -0700 Subject: [Tutor] help In-Reply-To: <20011010230531.12021.qmail@web13906.mail.yahoo.com> Message-ID: <4.2.0.58.20011010203117.00bf1870@pop3.norton.antivirus> At 04:05 PM 10/10/2001 -0700, james middendorff wrote: >I have fixed my last post but I do have a question, I would like to keep >looping this over and over until you type quit,thanks for the help! What might trigger an ioerror is the program tries to open a file that doesn't exist. That's all you need to trap with the try: except: syntax. The stuff about raw_input doesn't really need to be in a try block. In other words, this would work better: def getfile(): import os, sys while 1: # endless loop filename = raw_input("What file? ('q' to quit): ") if filename == 'q': break # escape from loop try: inp = open(filename,"r") print # blank line for line in inp.readlines(): print line, # note comma to suppress extra \n except IOError: print "That's not a real file!" # upon exiting to loop, flow continues here sys.exit() # I comment this out cuz I'm in shell mode >>> getfile() What file? ('q' to quit): duh.txt That's not a real file! What file? ('q' to quit): readme.txt This is Python version 2.2 ========================== Copyright (c) 2001 Python Software Foundation. All rights reserved. Copyright (c) 2000 BeOpen.com. All rights reserved. ... Kirby From wmperry@swbell.net Thu Oct 11 05:01:04 2001 From: wmperry@swbell.net (William Perry) Date: Wed, 10 Oct 2001 23:01:04 -0500 Subject: [Tutor] Help In-Reply-To: References: Message-ID: <200110102301040710.0D6C71F4@mail.swbell.net> in Mark Lutz's Programing Python example 7-31 he uses 2 linked scrollbars (sliders) to demonstrate useage. This might help (??) *********** REPLY SEPARATOR *********** On 10/10/01 at 11:12 AM Danny Yoo wrote: >On Tue, 9 Oct 2001, Glauco Silva wrote: > >> I would like to know how i can to do one Scrollbar to be linked with >> two Listbox if it's possible . Thank you Glauco > > From dyoo@hkn.eecs.berkeley.edu Thu Oct 11 08:00:00 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 11 Oct 2001 00:00:00 -0700 (PDT) Subject: [Tutor] Help In-Reply-To: <200110102301040710.0D6C71F4@mail.swbell.net> Message-ID: On Wed, 10 Oct 2001, William Perry wrote: > in Mark Lutz's Programing Python example 7-31 he uses 2 linked > scrollbars (sliders) to demonstrate useage. This might help (??) Cool; can anyone post that example up? I've donated my copy of Programming Python away... guess I know what my next book purchase will be tomorrow... *grin* From agauld@crosswinds.net Thu Oct 11 08:13:56 2001 From: agauld@crosswinds.net (agauld@crosswinds.net) Date: Thu, 11 Oct 2001 08:13:56 +0100 Subject: [Tutor] ONline tutor Message-ID: <07210120359994@mailth4.freenet.co.uk> My Crosswinds site is now fully restored but as previously mentioned I am now moving the master site to a new service provider. The new location will be: http://www.freenetpages.co.uk/hp/alan.gauld/ This site has: - no adverts - allows ftp access(much faster than web/http) and, within the UK at least, is a lot faster than crosswinds. If somebody in the US could confirm that speed is acceptable from there then I will complete the transfer process. (The English and Spanish sites are already there.) Alan G. From ignacio@openservices.net Thu Oct 11 08:36:37 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Thu, 11 Oct 2001 03:36:37 -0400 (EDT) Subject: [Tutor] ONline tutor In-Reply-To: <07210120359994@mailth4.freenet.co.uk> Message-ID: On Thu, 11 Oct 2001 agauld@crosswinds.net wrote: > My Crosswinds site is now fully restored but as previously > mentioned I am now moving the master site to a new service > provider. > > The new location will be: > > http://www.freenetpages.co.uk/hp/alan.gauld/ > > This site has: > - no adverts I think I speak for everyone but advertisers when I say WOOT! > - allows ftp access(much faster than web/http) > and, within the UK at least, is a lot faster than crosswinds. > If somebody in the US could confirm that speed is > acceptable from there then I will complete the transfer > process. (The English and Spanish sites are already there.) Good responsiveness. A bit spotty on downloading the tarball, but the HTML and images were quite quick via ADSL. -- Ignacio Vazquez-Abrams From nhytro-python@web.de Thu Oct 11 10:27:32 2001 From: nhytro-python@web.de (Sharriff Aina) Date: Thu, 11 Oct 2001 11:27:32 +0200 Subject: [Tutor] PyTix examples/Tutorials Message-ID: <200110110927.f9B9RWu18324@mailgate5.cinetic.de> Hello! can anyone point me to a good PyTix tutorial? the PyTix homepage does not help a bit, it refers one to the TCL/TK homepage. If someone hast a simple "Helloworld" using a mixture of Tkinter an TIX it would suffice also. Thanks so much Sharriff _______________________________________________________________________ 1.000.000 DM gewinnen - kostenlos tippen - http://millionenklick.web.de IhrName@web.de, 8MB Speicher, Verschluesselung - http://freemail.web.de From toodles@yifan.net Thu Oct 11 12:10:13 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Thu, 11 Oct 2001 19:10:13 +0800 Subject: [Tutor] ONline tutor References: Message-ID: <001701c15245$4d7ec820$0300a8c0@sun> > I think I speak for everyone but advertisers when I say WOOT! I'll second that! > Good responsiveness. A bit spotty on downloading the tarball, but the HTML and > images were quite quick via ADSL. And that. (Perth, Western Australia also on ADSL) Andrew From rick@niof.net Thu Oct 11 15:23:45 2001 From: rick@niof.net (Rick Pasotto) Date: Thu, 11 Oct 2001 10:23:45 -0400 Subject: [Tutor] Help In-Reply-To: <200110102301040710.0D6C71F4@mail.swbell.net> References: <200110102301040710.0D6C71F4@mail.swbell.net> Message-ID: <20011011102345.A13058@tc.niof.net> On Wed, Oct 10, 2001 at 11:01:04PM -0500, William Perry wrote: > in Mark Lutz's Programing Python example 7-31 he uses 2 linked > scrollbars (sliders) to demonstrate useage. This might help (??) But the question was about *one* scrollbar linked to two listboxes. > *********** REPLY SEPARATOR *********** > > On 10/10/01 at 11:12 AM Danny Yoo wrote: > > >On Tue, 9 Oct 2001, Glauco Silva wrote: > > > >> I would like to know how i can to do one Scrollbar to be linked > >> with two Listbox if it's possible . Thank you Glauco -- Hence, if anything is self-evident, it is this: law is the organization of the natural right to legitimate self-defense, it is the substitution of collective force for individual forces, to act in the sphere in which they have the right to act, to do what they have the right to do: to guarantee security of person, liberty, and property rights, to cause justice to reign over all. -- Frédéric Bastiat (1801-1850) Rick Pasotto rickp@telocity.com http://www.niof.net From lonetwin Thu Oct 11 17:28:56 2001 From: lonetwin (lonetwin) Date: Thu, 11 Oct 2001 21:58:56 +0530 (IST) Subject: [Tutor] Variables in Threaded functions Message-ID: Hi all ye good people, I'm kinda new to threaded programming in python (in any language for that matter !!). I'd like somebody to clear this up for me. I want to write a class that inherits from threading.Thread, whose run() function runs a loop that looks at a self.sequence, if there is something left in that sequence it goes and does something(self.sequence.pop()). Now a limited (say 3) threads would execute. My understanding is (correct me if I'm wrong) all the threads share the same self.sequence (if they don't how do I make them share a sequence ....without having to put in a global sequence ??) and also I'm uncertain about the implications of doing such things (shud I use locks ?? ...if I shud....how do I do that ??) Basically I want someone to explain how this code works and the implications of doing such things on a larger scale: ======================================================================== import threading import time class Strand(threading.Thread): bag = range(100) def __init__(self): threading.Thread.__init__(self) def run(self): while len(self.bag): print self.bag.pop(), def main(): Rope = [] for x in range(3): thread = Strand() Rope.append(thread) for thread in Rope: thread.start() print done if __name__ == '__main__': main() -- ---------------------------------------------- Every oak tree started out as a couple of nuts who stood their ground. Anonymous ---------------------------------------------- From arcege@speakeasy.net Thu Oct 11 17:58:35 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Thu, 11 Oct 2001 12:58:35 -0400 Subject: [Tutor] Help In-Reply-To: ; from gbcs1978@hotmail.com on Tue, Oct 09, 2001 at 03:07:23PM -0300 References: Message-ID: <20011011125835.A982@speakeasy.net> On Tue, Oct 09, 2001 at 03:07:23PM -0300, Glauco Silva wrote: > I would like to know how i can to do one Scrollbar to be linked with > two Listbox if it's possible . It's a little tricky, but you can do it. Unfortunately, there isn't great documentation even from the Tk side on the scrollbar callbacks (the documentation is there.. just not always straightforward). You need to make a new callback so the scrollbar calls the methods of both listboxes. Something like: import os from Tkinter import * from Tkinter import _cnfmerge class DoubleListbox(Frame): def __init__(self, master=None, cnf={}, **kws): # combine the configuration options into one cnf = _cnfmerge( (cnf, kws) ) Frame.__init__(self, master, cnf) self.sb = Scrollbar(self, command=self._scrollbar_from_sb) self.lb1 = Listbox(self, selectmode=SINGLE, yscrollcommand=self.self.sb.set) self.lb2 = Listbox(self, selectmode=SINGLE, yscrollcommand=self.self.sb.set) # here, we put the scrollbar on the extreme right of the frame self.sb.pack(side=RIGHT, fill=Y, expand=YES) self.lb1.pack(side=LEFT, fill=BOTH, expand=YES) self.lb2.pack(side=RIGHT, fill=BOTH, expand=YES) def _scrollbar_from_sb(self, *args): # if the argument from set is "scroll", then use the yview_scroll method # otherwise use the yview_moveto method of both listboxes meth_name = 'yview_' + args[0] args = args[1:] for obj in (self.lb1, self.lb2): meth = getattr(obj, meth_name) apply(meth, args) def _test(): root = Tk() dbllb = DoubleListbox(root, height=50, width=20) for file in os.listdir(os.curdir): if os.path.isdir(file): dbllb.lb1.insert(END, '%s/' % file) else: dbllb.lb2.insert(END, file) dbllb.pack(fill=BOTH, expand=YES) Button(root, text="Quit", command=root.quit).pack(side=BOTTOM) root.mainloop() if __name__ == '__main__': _test() Hope this helps. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | | Ailment info: http://www.speakeasy.org/~arcege/michaelwatch.html | From jerryl@europa.com Thu Oct 11 18:07:05 2001 From: jerryl@europa.com (Jerry Lake) Date: Thu, 11 Oct 2001 10:07:05 -0700 Subject: [Tutor] learning projects In-Reply-To: <20011011125835.A982@speakeasy.net> Message-ID: <000001c15277$287ab200$0103670a@europa.com> Can anyone give me some advise as to some projects to try with python that will help me gain a better understanding of it as well as programming in general I pretty much have access to any type of setup I need Thanks, Jerry Lake Interface Engineering Technician From shalehperry@home.com Thu Oct 11 18:12:47 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Thu, 11 Oct 2001 10:12:47 -0700 (PDT) Subject: [Tutor] learning projects In-Reply-To: <000001c15277$287ab200$0103670a@europa.com> Message-ID: On 11-Oct-2001 Jerry Lake wrote: > Can anyone give me some advise > as to some projects to try with > python that will help me gain > a better understanding of it as > well as programming in general > > I pretty much have access to any > type of setup I need > find some thing you use and reimplement it in python. Or look around the web for CS class programming assignments and do them in python. From rob@jam.rr.com Thu Oct 11 18:24:42 2001 From: rob@jam.rr.com (Rob Andrews) Date: Thu, 11 Oct 2001 12:24:42 -0500 Subject: [Tutor] learning projects In-Reply-To: <000001c15277$287ab200$0103670a@europa.com> References: <20011011125835.A982@speakeasy.net> Message-ID: <3BC58F8A.7940.10470A2@localhost> On 11 Oct 2001, at 10:07, Jerry Lake wrote: > Can anyone give me some advise > as to some projects to try with > python that will help me gain > a better understanding of it as > well as programming in general > Useless Python: http://www.lowerstandard.com/python/ Lots of projects and ideas, complete with a ton of code to play with. You can even change someone else's code around, send it in, and see it posted on the site. Plus, the site features programming contest problems and a pretty decent collection of links. Rob From lkvam@venix.com Thu Oct 11 18:35:30 2001 From: lkvam@venix.com (Lloyd Kvam) Date: Thu, 11 Oct 2001 13:35:30 -0400 Subject: [Tutor] learning projects References: <000001c15277$287ab200$0103670a@europa.com> Message-ID: <3BC5D862.24FCCCCF@venix.com> This site looks good to me. A lot depends on your interests. http://www.freenetpages.co.uk/hp/alan.gauld/ Many of the Python books include lots of sample code. The oreilly site has the samples from "Python Programming on Win32". If you are stuck in Windows, this book is great. The sample code includes large enough chunks to represent fairly real programs. I've adopted many ideas that were shown in their accounting examples. Jerry Lake wrote: > > Can anyone give me some advise > as to some projects to try with > python that will help me gain > a better understanding of it as > well as programming in general > > I pretty much have access to any > type of setup I need > > Thanks, > > Jerry Lake > Interface Engineering Technician > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From lkvam@venix.com Thu Oct 11 18:45:39 2001 From: lkvam@venix.com (Lloyd Kvam) Date: Thu, 11 Oct 2001 13:45:39 -0400 Subject: [Tutor] learning projects References: <000001c15277$287ab200$0103670a@europa.com> <3BC5D862.24FCCCCF@venix.com> Message-ID: <3BC5DAC3.FDDDC4E3@venix.com> I forgot another very good site: http://gnosis.cx/publish/tech_index.html Most of these articles were written for other sites & publications. I have found them to be very useful for improving my Python skills. Lloyd Kvam wrote: > > This site looks good to me. A lot depends on your interests. > http://www.freenetpages.co.uk/hp/alan.gauld/ > > Many of the Python books include lots of sample code. The oreilly site has the samples from "Python Programming on Win32". If you are stuck in Windows, this book is great. The sample code includes large enough chunks to represent fairly real > programs. I've adopted many ideas that were shown in their accounting examples. > > Jerry Lake wrote: > > > > Can anyone give me some advise > > as to some projects to try with > > python that will help me gain > > a better understanding of it as > > well as programming in general > > > > I pretty much have access to any > > type of setup I need > > > > Thanks, > > > > Jerry Lake > > Interface Engineering Technician > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- > Lloyd Kvam > Venix Corp. > 1 Court Street, Suite 378 > Lebanon, NH 03766-1358 > > voice: 603-443-6155 > fax: 801-459-9582 > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From boud@valdyas.org Thu Oct 11 20:03:16 2001 From: boud@valdyas.org (Boudewijn Rempt) Date: Thu, 11 Oct 2001 21:03:16 +0200 Subject: [Tutor] Variables in Threaded functions In-Reply-To: References: Message-ID: <200110111903.f9BJ3Mx10101@calcifer.valdyas.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Thursday 11 October 2001 18:28, lonetwin wrote: > =09 I want to write a class that inherits from threading.Thread, > whose run() function runs a loop that looks at a self.sequence, > if there is something left in that sequence it goes and does > something(self.sequence.pop()). Now a limited (say 3) threads would > execute. My understanding is (correct me if I'm wrong) all the threads > share the same self.sequence (if they don't how do I make them share a > sequence ....without having to put in a global sequence ??) and also > I'm uncertain about the implications of doing such things (shud I use > locks ?? ...if I shud....how do I do that ??) If you want all threads to share something, you do need to have an object that is accessible to all of them. However, accessing a shared object from more than one thread at a time is a recipe for disaster, so you need to create a lock object, and acquire() that lock before every access. This is how I rewrote your script: - --- import threading, time class Strand(threading.Thread): def __init__(self, bag, lock): """The bag and the lock are shared objects, passed to the threads in their constructors. Another strategy is to make them global, but that's not half as neat.""" threading.Thread.__init__(self) self.bag=3Dbag self.lock=3Dlock def run(self): # getName() tells us which thread is started print "Started " + self.getName() # We keep running until something gives us a break while 1: # We acquire the lock - in Java objects can be their own # locks, and you can synchronize() on an object. In Python # you need a separate lock object, and explicitly # acquire() that lock. If one thread accesses the # resources the lock is supposed to protect, without # acquiring it, then your concurrency is hosed. Caveat # delendor.=20 self.lock.acquire() # Always encapsulate usage of the locked object in a # try... finally block: if the lock isn't released through # some exception, all other threads would be blocked. try: # If the bag is empty, we quit. if len(self.bag) =3D=3D 0: break # Print the popped value print "thread", self.getName(), ": ", self.bag.pop() finally: # Whatever happens, always release the lock. self.lock.release() # Sleep a bit. A timeslice is long enough to pop the whole # bag in the first timeslice of the first thread. time.sleep(1) def main(): Rope =3D [] # The shared object and the shared lock sharedBagOfGoodies =3D range(100) sharedBagLock =3D threading.Lock() =20 for x in range(3): thread =3D Strand(sharedBagOfGoodies, sharedBagLock) Rope.append(thread) =20 for thread in Rope: print thread.getName() thread.start() =20 print "done" if __name__ =3D=3D '__main__': main() - --- > Basically I want someone to explain how this code works and the > implications of doing such things on a larger scale: > Threaded programming on a large scale is _difficult_. I'm not kidding, my day job is working on an agent platform that can handle thousands of concurrent agents and system processes, all implemented using threads (except that the agents themselves share a pool of threads and run cooperatively), I am continually running into threading problems. On the other hand, it's fun, too. You might like my article at Informit=20 on Python an microthreads (search for rempt - they don't provide direct links - http://www.informit.com). Another nice link:=20 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65202/index_txt In this simple example, you won't encounter any race conditions by not locking, but that is no indication of future results. - --=20 Boudewijn Rempt | http://www.valdyas.org -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE7xez1N8fj6DnPxOgRAlZ+AKCw0x04HWRrFvt9qn1pQNlUxD9JmwCeJ2Vi +Egfh3pCmKdUif9J2jdT/38=3D =3DXg7d -----END PGP SIGNATURE----- From dyoo@hkn.eecs.berkeley.edu Thu Oct 11 20:14:15 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 11 Oct 2001 12:14:15 -0700 (PDT) Subject: [Tutor] ONline tutor In-Reply-To: <001701c15245$4d7ec820$0300a8c0@sun> Message-ID: On Thu, 11 Oct 2001, Andrew Wilkins wrote: > > I think I speak for everyone but advertisers when I say WOOT! > > I'll second that! > > > Good responsiveness. A bit spotty on downloading the tarball, but > the HTML and > images were quite quick via ADSL. > > And that. (Perth, Western Australia also on ADSL) Feels fast here (Stanford, CA) too! Looks great! From rufmetal@home.com Fri Oct 12 04:18:56 2001 From: rufmetal@home.com (Chris Keelan) Date: Thu, 11 Oct 2001 22:18:56 -0500 Subject: [Tutor] Strange modulus problem Message-ID: <01101122185600.00949@tygesen> I'm working on a bit of code to determine all of the factors up to and including a number entered by the user. Here's my code: #!/usr/bin/python import string num=raw_input("Enter a number: ") num_int=string.atoi(num) factor_range= range(1, num_int + 1) for item in factor_range: if num_int % item > 0: factor_range.remove(item) print 'The factors are %s' % factor_range But when I run it, I get the following weird output: >>Enter a number: 6 The factors are [1, 2, 3, 5, 6] Why doesn't '5' fail the if test and get removed? If I modify the code so that it prints the modulus of each item, 5 correctly evalutates to '1'. What gives? - Chris From urnerk@qwest.net Fri Oct 12 04:22:57 2001 From: urnerk@qwest.net (Kirby Urner) Date: Thu, 11 Oct 2001 20:22:57 -0700 Subject: [Tutor] Strange modulus problem In-Reply-To: <01101122185600.00949@tygesen> Message-ID: <4.2.0.58.20011011200732.00a6ec10@pop3.norton.antivirus> > >Why doesn't '5' fail the if test and get removed? If I modify >the code so that it prints the modulus of each item, 5 correctly >evalutates to '1'. What gives? > >- Chris This has to do with iterating over the object you're also modifying. The code below works because it iterates over a copy of factor_range (the effect of putting [:] after it): >>> def factors(n): factor_range = range(1, n + 1) for item in factor_range[:]: if n % item: factor_range.remove(item) return factor_range >>> factors(6) [1, 2, 3, 6] >>> factors(20) [1, 2, 4, 5, 10, 20] (Note also that n%item is true if non-zero, so you don't really need the additional >0). In the your way of doing it, you don't actually get to test all the numbers in the range, because you yank an offender out of the line-up, shortening the list, so when the loop comes around and it iterates to the "next" item, it's hitting against a foreshortened list, meaning it skips over a value you wish it hadn't. You can study this behavior by inserting a line that prints the item being tested: >>> def factors(n): factor_range = range(1, n + 1) for item in factor_range: # not a copy print item # debug print if n % item: factor_range.remove(item) return factor_range >>> factors(10) 1 2 3 5 6 8 10 [1, 2, 4, 5, 7, 9, 10] You see that 4 wasn't tested, because the program yanks 3 (not a factor), and so the next candidate it hits if 5. Likewise, 7 and 9 sneak through. This is a common programming error in Python and you're lucky to stumble across it in such an illuminating manner. It's very good to make mistakes of this kind -- very text book. You have a promising career as a Pythoneer ahead of you (pardon the fortune cookie). Kirby From toodles@yifan.net Fri Oct 12 04:35:41 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Fri, 12 Oct 2001 11:35:41 +0800 Subject: [Tutor] Strange modulus problem References: <01101122185600.00949@tygesen> Message-ID: <000c01c152ce$f8a77830$0300a8c0@sun> I think what I have to say is right, if I'm not someone please correct me :) > I'm working on a bit of code to determine all of the factors up to and > including a number entered by the user. Here's my code: > > #!/usr/bin/python > > import string > > num=raw_input("Enter a number: ") > num_int=string.atoi(num) > > factor_range= range(1, num_int + 1) > > for item in factor_range: > if num_int % item > 0: > factor_range.remove(item) "for" goes through the indices 0..len(factor_range) As you remove each item it decreases the size of factor_range, and the index that for points to next will contain something else. Example: >>> test_range=range(10) >>> for i in test_range: print i,test_range test_range.remove(i) 0 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 2 [1, 2, 3, 4, 5, 6, 7, 8, 9] 4 [1, 3, 4, 5, 6, 7, 8, 9] 6 [1, 3, 5, 6, 7, 8, 9] 8 [1, 3, 5, 7, 8, 9] So as you can see in the 2nd iteration it is pointing to index 1 as it should be, but this now points to "2". So to fix this you could do it one of these (untested) ways: 1) Preserve what you've done already factor_range=range(1,num_int+1) loop_range=factor_range[:] #copy contents for item in loop_range: if num_int % item > 0: loop_range.remove(item) 2) Do it the way I prefer to do it :) factors=[] for i in range(1,num_int+1): if num_int%i==0: factors.append(i) ...I'm sure there's still more ways. > Why doesn't '5' fail the if test and get removed? If I modify the code so > that it prints the modulus of each item, 5 correctly evalutates to '1'. What > gives? >>> fr=range(1,7) >>> for item in fr: print item,fr if 6%item>0: fr.remove(item) 1 [1, 2, 3, 4, 5, 6] 2 [1, 2, 3, 4, 5, 6] 3 [1, 2, 3, 4, 5, 6] 4 [1, 2, 3, 4, 5, 6] 6 [1, 2, 3, 5, 6] It's not even looking at 5 :) It gets to "4" and removes it, thus bringing the next index to point to "6". HTH Andrew > > - Chris > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From lonetwin@yahoo.com Fri Oct 12 11:08:35 2001 From: lonetwin@yahoo.com (lonetwin) Date: Fri, 12 Oct 2001 15:38:35 +0530 Subject: [Tutor] Variables in Threaded functions In-Reply-To: <200110111903.f9BJ3Mx10101@calcifer.valdyas.org> References: <200110111903.f9BJ3Mx10101@calcifer.valdyas.org> Message-ID: <01101215383501.21081@mercury.worli> Hi everybody, Thanx Boudewijn, for the quick answer. Now that I have fixed what I was trying to do...I have some more questions for you (an' everybody who might want to answer). You wrote: > If you want all threads to share something, you do need to have an > object that is accessible to all of them. However, accessing a shared > object from more than one thread at a time is a recipe for disaster, > so you need to create a lock object, and acquire() that lock before > every access. Right, I though as much. ********************************************* > This is how I rewrote your script: > ---- > import threading, time > > class Strand(threading.Thread): > > def __init__(self, bag, lock): > """The bag and the lock are shared objects, > passed to the threads in their constructors. Another > strategy is to make them global, but that's not half > as neat.""" > threading.Thread.__init__(self) > self.bag=bag > self.lock=lock <-------------------------snip--------------------------> Question 1: why is bag passed to Strand ??....what if I bag belongs to be the class ....like I did in my initial proggy ...is this a bad-thing in any manner vvvvvvvvvvv class Strand(threading.thread): bag = range(100) def __init__(self, lock): ..... ..... <-------------------------/snip----------------------------> > def run(self): > # getName() tells us which thread is started > print "Started " + self.getName() > # We keep running until something gives us a break > while 1: > # We acquire the lock - in Java objects can be their own > # locks, and you can synchronize() on an object. In Python > # you need a separate lock object, and explicitly > # acquire() that lock. If one thread accesses the > # resources the lock is supposed to protect, without > # acquiring it, then your concurrency is hosed. Caveat > # delendor. > self.lock.acquire() > # Always encapsulate usage of the locked object in a > # try... finally block: if the lock isn't released through > # some exception, all other threads would be blocked. > try: > # If the bag is empty, we quit. > if len(self.bag) == 0: > break > # Print the popped value > print "thread", self.getName(), ": ", self.bag.pop() > finally: > # Whatever happens, always release the lock. > self.lock.release() <----------------------snip--------------------------------> Question 2: Why .... def run(self): while 1: self.acquire() try: if len(self.bag) == 0: break else: doStuff() finally: self.lock.release() ....... instead of .... def run(self): self.acquire() try: while len(self.bag) !=0: doStuff() finally: self.lock.release() For me, this ^^^^ reads much better....but is there something I should know about ??? <---------------------------/snip----------------------> > # Sleep a bit. A timeslice is long enough to pop the whole > # bag in the first timeslice of the first thread. > time.sleep(1) > > def main(): > Rope = [] > # The shared object and the shared lock > sharedBagOfGoodies = range(100) > sharedBagLock = threading.Lock() > > for x in range(3): > thread = Strand(sharedBagOfGoodies, sharedBagLock) > Rope.append(thread) > > for thread in Rope: > print thread.getName() > thread.start() > > print "done" > > if __name__ == '__main__': > main() > ------- And finally Question 3: What if I have more that one bag ?? does one lock, lock-up all the shared objects ??....or should I lock.acquire() before every access to any one of the shared objects ?? Hope my questions make sense... Thanx for you patience Peace Steve ---------------------------------------------- Every oak tree started out as a couple of nuts who stood their ground. Anonymous ---------------------------------------------- From mailmgr2@i-55.com Fri Oct 12 20:09:07 2001 From: mailmgr2@i-55.com (Craig Carman) Date: Fri, 12 Oct 2001 19:09:07 Subject: [Tutor] Thank You! & Something for you Message-ID: PM20007:09:07 PM This is an HTML email message. If you see this, your mail client does not support HTML messages. ------=_NextPart_TPDTZDDFQH Content-Type: text/html;charset="iso-8859-1" Content-Transfer-Encoding: 7bit Untitled
You are receiving this email because your address was submitted to our system. Perhaps you made an auction inquiry, entered one of our contests or are an existing customer with an alternate email address we don't have documented. If, at any time, you wish to un-subscribe or edit your email preferences see the note below.
   See Shop Go .com
   wants to Thank You!

Dear Customers and Contest Entrants,

Like that dry toned, but humorous, guy on the canned beans commercial says, "Thank you for your support!" I want to do the same to be sure you know your business is appreciated. The people of SeeShopGo.com and I work hard to help you remember where you actually had fun shopping on-line looking at all the beautiful pictures of our 6,000+ jewelry items. You may remember, the place where you actually got real customer service. Anyway, thanks! We hope you will return to shop at SeeShopGo.com for several of you holiday gifts in the next few weeks.

Here is a great Special Offer / Special Price - Click Here to get you started!

Sterling Silver Matching Bracelet / Necklaces Sets only $9.00


Three chain designs are available for this special in various lengths. This Special Offer is only available for this email offer. These items aren't even listed in our huge selection in our web site shopping cart.

Choose from:
  • Figaro Design
  • Beaded Design
  • Snake Design
Sincerely,

Craig Carman, President

SeeShopGo, L.L.C.
1030 Canal Street
New Orleans, Louisiana
Toll Free Customer Support 1-866-DIA-SHOP(342-7467)

We appreciate your support and for your convenience we provide fully automated
Email Subscription Self-Management (subscribe / un-subscribe - click here).
------=_NextPart_TPDTZDDFQH-- From urnerk@qwest.net Sat Oct 13 01:48:23 2001 From: urnerk@qwest.net (Kirby Urner) Date: Fri, 12 Oct 2001 17:48:23 -0700 Subject: [Tutor] Variables in Threaded functions In-Reply-To: <01101215383501.21081@mercury.worli> References: <200110111903.f9BJ3Mx10101@calcifer.valdyas.org> <200110111903.f9BJ3Mx10101@calcifer.valdyas.org> Message-ID: <4.2.0.58.20011012172733.00c564a0@pop3.norton.antivirus> > > Question 1: why is bag passed to Strand ??....what if >I bag belongs to be the class ....like I did in my initial >proggy ...is this a bad-thing in any manner vvvvvvvvvvv Seems a non-idiomatic use of a class variable, but maybe it works -- I haven't tested it. >def run(self): > self.acquire() > try: > while len(self.bag) !=0: > doStuff() > finally: > self.lock.release() > > For me, this ^^^^ reads much better....but is there something >I should know about ??? Here your thread grabs the lock, then loops around while the bag isn't empty, sucking it dry, then, finally, it releases the lock. So what do the other threads get to do? Just wait around and watch while Mr. Greedy Gut hogs the entire bag I guess. >And finally Question 3: What if I have more that one bag ?? >does one lock, lock-up all the shared objects ??....or should >I lock.acquire() before every access to any one of the shared >objects ?? > >Hope my questions make sense... > >Thanx for you patience > >Peace >Steve Well, I'm not Mr. Threads (the previous respondant sounded way more knowledgable than I), but I think you should think of the lock as akin to the conch in 'Lord of the Flies'. Every read that? These kids get marooned on a tropical island and their culture gradually degenerates, but one convention is whoever holds this big shell in meetings is the one who gets to talk, and you pass this shell (conch) around to control the flow of speech -- similar to a "talking stick" in some native American traditions. The lock is a conch, and as long as one thread has it, the other threads block when trying to aquire it for themselves. Whichever thread is holding the conch has to explicitly release it, before the other would-be aquirers have a chance. However, as the previous respondant posted, it's up to you to write civilized thread code that actually asks permission before modifying data: If one thread accesses the resources the lock is supposed to protect, without acquiring it, then your concurrency is hosed. Caveat delendor. You-the-programmer put into your code where a thread should say "pretty please". But if you code up some bull-in-a-China-shop thread that doesn't even ask (doesn't try to aquire) but just goes ahead and attacks the bag, then all the other threads can do is watch in horror. No operating system police are going to keep the undisciplined thread from just charging around, doing whatever damage. In other words, the aquire(), release() convention simply provides a mechanism whereby you can establish a genteel arrangement among your threads, but doesn't involve any physical placement of locks on any data objects. Ergo, there's no question of needing multiple locks for each object -- they're not really locked, it's the threads that use the lock object to take turns doing whatever. Kirby PS: in 'Lord of the Flies', some bullies eventually get tired of the conch convention and break this final rule. Some fat kid, who was holding the conch at the time, protests, and pays with his life. A cheery book -- they make school kids read it so they can see why adults are so strict (left to your own devices, you'd make dead meat of each other in no time, is the message). From dyoo@hkn.eecs.berkeley.edu Sat Oct 13 02:52:30 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 12 Oct 2001 18:52:30 -0700 (PDT) Subject: [Tutor] Thank You! & Something for you [difflib in Python 2.1] In-Reply-To: PM20007:09:07 PM Message-ID: On Fri, 12 Oct 2001, Craig Carman wrote: > Choose from: > * Figaro Design > * Beaded Design > * Snake Design ^^^^^ You've reached Python-tutor, which, despite its name, has very little to do with "Python reticulatus". The name "Python" here refers to the highly regarded "Monty Python" comedy group. I guess "Python" could also refer, distantly, to the name of a really nice programming language. We're a group of tutors who help each other learn how to program, and your question has very little content. Still, even in the midst of your confusion, we can try to help. >From the snippet above, we could interpret that you're trying to get a user to choose from a list of specific choices, maybe something like this: ### What flavor of ice cream do you like the most? Choose from the following: * green tea * rocky road * vanilla * chocolate > Humperdinck I don't know about Humperdinck. Please try again. > banilla I don't know about banilla. Please try again. > vanilla ### Here's one possible implementation for this alternative-choosing function: ### def chooseAnAlternative(alternatives): while 1: choice = raw_input("> ") if choice in alternatives: return choice print "I don't know about %s. Please try again." % choice ### This works... but we notice that program is a little unfriendly: it doesn't accept any misspellings. Even if someone is one letter off, our program just clamps hands over its years and sings "I'm not listening..." But this can be fixed! We can make this program more forgiving with the extremely cool 'difflib' module that's new with Python 2.1: http://python.org/doc/current/lib/module-difflib.html difflib will, given a list of choices, try to find the very best choice, even if the user misspells a word: ### import difflib def chooseAnAlternative(alternatives): while 1: choice = raw_input("> ") best_match = difflib.get_close_matches(choice, alternatives, 1) if best_match: return best_match[0] print "I don't know about %s. Please try again." % choice ### Here's a small test of this improved chooseAnAlternative() function: ### >>> flavours = ['green tea', 'rocky road', 'vanilla', 'chocolate'] >>> chooseAnAlternative(flavours) > rookie I don't know about rookie. Please try again. > banilla 'vanilla' >>> chooseAnAlternative(['to bluff', 'true love']) > tooblaithe I don't know about tooblaithe. Please try again. > to blove 'true love' ### difflib does a very good job at trying to make sense out of the incomprehensible. From wsryu@fas.harvard.edu Sat Oct 13 03:14:22 2001 From: wsryu@fas.harvard.edu (William Ryu) Date: Fri, 12 Oct 2001 22:14:22 -0400 Subject: [Tutor] Curses module? In-Reply-To: Message-ID: <5.1.0.14.2.20011012221118.00ae94d0@pop.fas.harvard.edu> I was interested in learning the curses module, but when I fired up my 2.1.1 session I couldn't import it: Python 2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> Traceback (most recent call last): File "", line 1, in ? ImportError: No module named curses >>> Curiously, it's not anywhere to be found in /lib. I guess I'm missing something. Isn't the curses module supposed to be in the /lib folder, even for the Windows distribution? Thanks, -willryu From dyoo@hkn.eecs.berkeley.edu Sat Oct 13 03:51:14 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 12 Oct 2001 19:51:14 -0700 (PDT) Subject: [Tutor] Curses module? In-Reply-To: <5.1.0.14.2.20011012221118.00ae94d0@pop.fas.harvard.edu> Message-ID: On Fri, 12 Oct 2001, William Ryu wrote: > I was interested in learning the curses module, but when I fired up my > 2.1.1 session I couldn't import it: > > Python 2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)] on win32 > Type "copyright", "credits" or "license" for more information. > >>> > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named curses > >>> > > Curiously, it's not anywhere to be found in /lib. I guess I'm missing > something. Isn't the curses module supposed to be in the /lib folder, even > for the Windows distribution? There's a 'pdcurses' library that's supposed to be simliar to the standard Unix curses library: http://www.mikroplan.com.pl/~mak/python/ although I'm not quite sure if this works well. Does anyone else have experience with it? From scanning through the net, I've gotten the impression that not many people are interested in curses programming, so not much attention has been placed on making it work for Windows right out of the box. And that's a shame. There's also a library specifically for Windows that sorta provides curses behavior called 'console', written by Fredrik Lundh: http://w1.132.telia.com/~u13212494/efflib/console/ Good luck! From wheelege@tsn.cc Sat Oct 13 03:54:40 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Sat, 13 Oct 2001 12:54:40 +1000 Subject: [Tutor] Thank You! & Something for you [difflib in Python 2.1] References: Message-ID: <007a01c15392$67e24fe0$9aa616ca@ACE> LOL! > > <...> > > difflib does a very good job at trying to make sense out of the > incomprehensible. > Kind of like a certain person I know :) (btw nice piece on difflib) From urnerk@qwest.net Sat Oct 13 04:03:37 2001 From: urnerk@qwest.net (Kirby Urner) Date: Fri, 12 Oct 2001 20:03:37 -0700 Subject: [Tutor] Curses module? In-Reply-To: <5.1.0.14.2.20011012221118.00ae94d0@pop.fas.harvard.edu> References: Message-ID: <4.2.0.58.20011012195907.00c55220@pop3.norton.antivirus> At 10:14 PM 10/12/2001 -0400, William Ryu wrote: >I was interested in learning the curses module, but when I fired up my >2.1.1 session I couldn't import it: Pretty much a Unix thing. Here's a thread that might interest you: http://groups.yahoo.com/group/python-list/message/125037 Looks like you're in for a fair amount of work if you want Win32 curses. Easier to just dual boot Linux IMO, which will let you play with fork module and such as well. Kirby From tonycervone@netzero.net Sat Oct 13 11:38:16 2001 From: tonycervone@netzero.net (tonycervone) Date: Sat, 13 Oct 2001 06:38:16 -0400 Subject: [Tutor] My first script within a game program Message-ID: <000801c153d3$2c234b80$fd84f4d1@w9y5d5> This is a multi-part message in MIME format. ------=_NextPart_000_0005_01C153B1.A3BA58E0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I am learning Python and am trying to write a script that uses = specific(game ) program functions for additional functionality withing = the game play. The program is a flight sim and the two functions that I = am trying to use are: LoadMetar() and EndSituation(). The LoadMetar() = will call a text file, and the EndSituation() will reset the particular = situation so that a new situation can be loaded without having to start = the game. Here's the script so far: from fly import * metarFlag =3D 0 def Main(dt): global metarFlag if (metarFlag =3D=3D 0): LoadMetar("Metar\InfoMetar.txt") NoticeToUser(" loading InfoMetar Weather v1.0", 10.0) metarFlag =3D 1 With this script placed in the program, I can successfully load the = InfoMetar.txt when I load my first situation. The question is that if I = want to load a new situation I need to add the EndSituation() function = somewhere in the script in order to reset, I suspect, some flag so that = when I start a new situation the loadMetar() function is loaded again. = Presently, I need to restart the Game whenever I want to load a new = situation. I hope I have provided enough clues. Unfortunately, I don't = have any docs, thus the difficulty. tony cervone ------=_NextPart_000_0005_01C153B1.A3BA58E0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I am learning Python and am trying to = write a=20 script that uses specific(game ) program functions for additional=20 functionality withing the game play. The program is a flight sim and the = two=20 functions that I am trying to use are: LoadMetar() and EndSituation(). = The=20 LoadMetar() will call a text file, and the EndSituation() will reset the = particular situation so that a new situation can be loaded without = having to=20 start the game.   Here's the script so far:

from fly import *

metarFlag =3D 0

def Main(dt):

global metarFlag

if (metarFlag =3D=3D 0):

LoadMetar("Metar\InfoMetar.txt")

NoticeToUser(" loading InfoMetar Weather v1.0", 10.0)

metarFlag =3D 1

With this script placed in the program, I can = successfully=20 load the InfoMetar.txt when I load my first situation. The question is = that if I=20 want to load a new situation I need to add the EndSituation() function = somewhere=20 in the script in order to reset, I suspect, some flag so that when = I start=20 a new situation the loadMetar() function is loaded again. = Presently, I=20 need to restart the Game whenever I want to load a new situation.  = I hope I=20 have provided enough clues. Unfortunately, I don't have any docs, thus = the=20 difficulty. tony cervone

 

------=_NextPart_000_0005_01C153B1.A3BA58E0-- ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From wheelege@tsn.cc Sat Oct 13 13:07:49 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Sat, 13 Oct 2001 22:07:49 +1000 Subject: [Tutor] My first script within a game program References: <000801c153d3$2c234b80$fd84f4d1@w9y5d5> Message-ID: <00c101c153df$b8492ba0$9aa616ca@ACE> Howdy Tony, Next time your posting, please keep to plain text and indent your code - thanks :) Anywho, onto your question... metarFlag = 0 def Main(dt): global metarFlag if (metarFlag == 0): LoadMetar("Metar\InfoMetar.txt") NoticeToUser(" loading InfoMetar Weather v1.0", 10.0) metarFlag = 1 > With this script placed in the program, I can successfully load the InfoMetar.txt when I load my first situation. The > question is that if I want to load a new situation I need to add the EndSituation() function somewhere in the script in > order to reset, I suspect, some flag so that when I start a new situation the loadMetar() function is loaded again. > Presently, I need to restart the Game whenever I want to load a new situation. I hope I have provided enough clues. > Unfortunately, I don't have any docs, thus the difficulty. tony cervone No docs? Try www.python.org for all the latest documentation that comes with python. It sounds like all you need to do is add a question to the user when they want to quit - or perhaps make the 'Reset Situation' option in a menu somewhere? Or perhaps as a keyboard shortcut? The code should be simple enough (sans GUI :) and all you would need to do is then call EndSituation() once they respond. I can't help but feel I'm missing the point here. Could you please repost with a bit more detail? Thanks, Glen From wheelege@tsn.cc Sat Oct 13 14:04:16 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Sat, 13 Oct 2001 23:04:16 +1000 Subject: [Tutor] My first script within a game program References: <000801c153d3$2c234b80$fd84f4d1@w9y5d5> <00c101c153df$b8492ba0$9aa616ca@ACE> <000701c153e1$f7a642e0$9e8df4d1@w9y5d5> Message-ID: <00cf01c153e7$921cdb40$9aa616ca@ACE> > Hi Glen. > Sorry for the text; I am learning. :) Also, next time you reply try using 'Reply All' - then it will be posted to the list and me, *insert witty quote about more people being better than one here*. > To be more specific about my dilemma..... > 1. Is a function like EndSituation() complete, or do I need to place > anything after calling it, that is, to make sure that it works. If it can > stand by itself, I think I know how to use it. I'm not sure, it would really depend on what EndSituation exactly does. Perhaps a few test runs could help you figure it out? Things like the position of your plane, the landscape, things regarding the default values for the situation would need to be preserved somewhere - but that should all be within the function. I'd try it out. > 2. the lack of docs referred to those that come with the game. Ah. Probably a silly question but have you tried 'print EndSituation.__doc__'? That could help :) If all the functions have docstrings (.__doc__ attributes) then you can cook up a little loop that will print out all the documentation for you. The way to do this is using the built-in dir function which when called returns a list of all the current object in the namespace. If that's just a whole bunch of gibberish, then we can help you out :) > 3. It seems that once the function LoadMetar() is called, it stays in the > program. My dilemma is that the script in which this fuction resides is run > once within the program. So, it seems, that when a brand new situation is > loaded from the program, the same script is loaded, but this time it has to > check for some flag that resets the LoadMetar(). I think I'm starting to understand what you mean. The problem is that the script cannot really call itself from within itself? I don't think that would be the behaviour of EndSituation - more likely the function halts the current situation and restarts with a new one (perhaps a clone of the old) but it wouldn't call the script from the beginning again. Is there a way to ask for user input once within the program? If you can, then a simple command from the user could invoke EndSituation and the results could be observed directly. If not, try altering your script to something like... def Main(dt): global metarFlag if (metarFlag == 0): LoadMetar("Metar\InfoMetar.txt") NoticeToUser(" loading InfoMetar Weather v1.0", 10.0) metarFlag = 1 NoticeToUser(" Ending the situation, look out!", 10.0) ## what does this number do? EndSituation() ## does EndSituation take any arguments? > The good thing about trying to explain this is that it's helping me figure > out the problem more clearly. :) Good luck! Glen From rufmetal@home.com Sat Oct 13 17:24:27 2001 From: rufmetal@home.com (Chris Keelan) Date: Sat, 13 Oct 2001 11:24:27 -0500 Subject: [Tutor] Strange modulus problem In-Reply-To: <4.2.0.58.20011011200732.00a6ec10@pop3.norton.antivirus> References: <4.2.0.58.20011011200732.00a6ec10@pop3.norton.antivirus> Message-ID: <01101311242700.01473@tygesen> On Thu, 11 Oct 2001, Kirby Urner wrote: > This has to do with iterating over the object you're > also modifying. When you explain it that way, it makes perfect sense! For some reason I didn't think that the 'for' iteration worked by index. Perhaps there was a little gnome who took all of the objects out of a list, laid them out on a table and picked them up, one-by-one saying "If I divide six by this, will my remainder be zero? Nope? Well throw it out then." ;o) > > The code below works because it iterates over a copy Which is how I'm gonna do this from now on. [snip] > This is a common programming error in Python and you're > lucky to stumble across it in such an illuminating > manner. It's very good to make mistakes of this kind > -- very text book. You have a promising career as a > Pythoneer ahead of you (pardon the fortune cookie). You sound like my singing teacher. He told me that sometimes it was better to be loudly wrong than to be quietly right. Thanks for the help, Kirby. - Chris From rufmetal@home.com Sat Oct 13 17:36:15 2001 From: rufmetal@home.com (Chris Keelan) Date: Sat, 13 Oct 2001 11:36:15 -0500 Subject: [Tutor] Strange modulus problem In-Reply-To: <01101122185600.00949@tygesen> References: <01101122185600.00949@tygesen> Message-ID: <01101311361501.01473@tygesen> On Thu, 11 Oct 2001, Chris Keelan wrote: Thanks Andrew and Scott. My script now works perfectly! - Chris From rufmetal@home.com Sat Oct 13 18:03:04 2001 From: rufmetal@home.com (Chris Keelan) Date: Sat, 13 Oct 2001 12:03:04 -0500 Subject: [Tutor] Now I have a variable-passing problem! Message-ID: <01101312030400.01555@tygesen> Thanks again to all who helped me with my list/iteration question. Now I've made the following mess for myself: def get_number(): rawNum=raw_input("Enter a number between 0 and 10,000: ") try: num_int = string.atoi(rawNum) if (0 > num_int) or (num_int > 10000): print 'Sorry, that number is not between 0 and 10000' get_number() except ValueError: print "Try again. We need an integer between 0 and 10,000" get_number() return rawNum >>Enter a number between 0 and 10,000: a >>Try again. We need an integer between 0 and 10,000 >>Enter a number between 0 and 10,000: 50 Which, when I try to unit-test by entering a letter instead of an integer, gives me the following. Traceback (innermost last): File "./6-8.py", line 127, in ? pretty=give_me_english(list) File "./6-8.py", line 114, in give_me_english ones = string.atoi(digit_list[0]) ValueError: invalid literal for atoi(): a Here's what I don't understand: get_number() is called (function A) and assigns a raw input value to rawNum. When rawNum fails the "string.atoi" test, the function calls itself again (function B), assinging a new value to rawNum which does not get passed to the function A when the function B terminates. How do I (re)write the code so that function B passes the correct value to function A? Should I even bother or just re-write the body of the if-test to re-prompt without a recursive call? - Chris From toodles@yifan.net Sat Oct 13 17:35:23 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Sun, 14 Oct 2001 00:35:23 +0800 Subject: [Tutor] Now I have a variable-passing problem! References: <01101312030400.01555@tygesen> Message-ID: <001d01c15405$0fdd3710$0300a8c0@sun> Heya Chris, *changes order of your message* > Should I even bother or just re-write the body of the if-test to re-prompt > without a recursive call? IMHO the recursive calls aren't very useful here. Here's how I'd have it written: (Note that you can use int('123') to convert from a string to an integer. I'm not sure which version of Python that was introduced in, but it can easily be changed back to string.atoi().) def get_number(): while 1: rawNum=raw_input("Enter a number between 0 and 10,000: ") try: num_int=int(rawNum) if not (num_int<0 or num_int>10000): return num_int else: print 'Sorry, that number is not between 0 and 10,000' except ValueError: print 'Try again. We need an integer between 0 and 10,000' >>> get_number() Enter a number between 0 and 10,000: a Try again. We need an integer between 0 and 10,000 Enter a number between 0 and 10,000: 50 50 HTH Andrew > Thanks again to all who helped me with my list/iteration question. > > Now I've made the following mess for myself: > > > def get_number(): > rawNum=raw_input("Enter a number between 0 and 10,000: ") > > try: > num_int = string.atoi(rawNum) > if (0 > num_int) or (num_int > 10000): > print 'Sorry, that number is not between 0 and 10000' > get_number() > > > except ValueError: > print "Try again. We need an integer between 0 and 10,000" > get_number() > > return rawNum > > >>Enter a number between 0 and 10,000: a > >>Try again. We need an integer between 0 and 10,000 > >>Enter a number between 0 and 10,000: 50 > > Which, when I try to unit-test by entering a letter instead of an integer, > gives me the following. > > Traceback (innermost last): > File "./6-8.py", line 127, in ? > pretty=give_me_english(list) > File "./6-8.py", line 114, in give_me_english > ones = string.atoi(digit_list[0]) > ValueError: invalid literal for atoi(): a > > > Here's what I don't understand: get_number() is called (function A) and > assigns a raw input value to rawNum. When rawNum fails the "string.atoi" > test, the function calls itself again (function B), assinging a new value to > rawNum which does not get passed to the function A when the function B > terminates. How do I (re)write the code so that function B passes the > correct value to function A? > > > - Chris > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From toodles@yifan.net Sat Oct 13 17:35:23 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Sun, 14 Oct 2001 00:35:23 +0800 Subject: [Tutor] Now I have a variable-passing problem! References: <01101312030400.01555@tygesen> Message-ID: <001d01c15405$0fdd3710$0300a8c0@sun> Heya Chris, *changes order of your message* > Should I even bother or just re-write the body of the if-test to re-prompt > without a recursive call? IMHO the recursive calls aren't very useful here. Here's how I'd have it written: (Note that you can use int('123') to convert from a string to an integer. I'm not sure which version of Python that was introduced in, but it can easily be changed back to string.atoi().) def get_number(): while 1: rawNum=raw_input("Enter a number between 0 and 10,000: ") try: num_int=int(rawNum) if not (num_int<0 or num_int>10000): return num_int else: print 'Sorry, that number is not between 0 and 10,000' except ValueError: print 'Try again. We need an integer between 0 and 10,000' >>> get_number() Enter a number between 0 and 10,000: a Try again. We need an integer between 0 and 10,000 Enter a number between 0 and 10,000: 50 50 HTH Andrew > Thanks again to all who helped me with my list/iteration question. > > Now I've made the following mess for myself: > > > def get_number(): > rawNum=raw_input("Enter a number between 0 and 10,000: ") > > try: > num_int = string.atoi(rawNum) > if (0 > num_int) or (num_int > 10000): > print 'Sorry, that number is not between 0 and 10000' > get_number() > > > except ValueError: > print "Try again. We need an integer between 0 and 10,000" > get_number() > > return rawNum > > >>Enter a number between 0 and 10,000: a > >>Try again. We need an integer between 0 and 10,000 > >>Enter a number between 0 and 10,000: 50 > > Which, when I try to unit-test by entering a letter instead of an integer, > gives me the following. > > Traceback (innermost last): > File "./6-8.py", line 127, in ? > pretty=give_me_english(list) > File "./6-8.py", line 114, in give_me_english > ones = string.atoi(digit_list[0]) > ValueError: invalid literal for atoi(): a > > > Here's what I don't understand: get_number() is called (function A) and > assigns a raw input value to rawNum. When rawNum fails the "string.atoi" > test, the function calls itself again (function B), assinging a new value to > rawNum which does not get passed to the function A when the function B > terminates. How do I (re)write the code so that function B passes the > correct value to function A? > > > - Chris > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From arcege@speakeasy.net Sat Oct 13 17:39:33 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Sat, 13 Oct 2001 12:39:33 -0400 Subject: [Tutor] Strange modulus problem In-Reply-To: <01101311242700.01473@tygesen>; from rufmetal@home.com on Sat, Oct 13, 2001 at 11:24:27AM -0500 References: <4.2.0.58.20011011200732.00a6ec10@pop3.norton.antivirus> <01101311242700.01473@tygesen> Message-ID: <20011013123933.C982@speakeasy.net> On Sat, Oct 13, 2001 at 11:24:27AM -0500, Chris Keelan wrote: > On Thu, 11 Oct 2001, Kirby Urner wrote: > > > This has to do with iterating over the object you're > > also modifying. > > When you explain it that way, it makes perfect sense! For some reason I > didn't think that the 'for' iteration worked by index. Perhaps there was a > little gnome who took all of the objects out of a list, laid them out on a > table and picked them up, one-by-one saying "If I divide six by this, will my > remainder be zero? Nope? Well throw it out then." Also, instead of removing items, you can append items to a new list: m = range(100) l = [] for i in m: if (i % 13) == 0: l.append( i ) print l [0, 13, 26, 39, 52, 65, 78, 91] Then there is no need to create a copy of the list, which could be expensive if the list is large, and not removing items from a list, which you can see is problematic. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From wheelege@tsn.cc Sun Oct 14 03:20:00 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Sun, 14 Oct 2001 12:20:00 +1000 Subject: [Tutor] Now I have a variable-passing problem! References: <01101312030400.01555@tygesen> Message-ID: <006101c15456$ba4529a0$c1a616ca@ACE> Hi, Since I couldn't see anything written by Andrew to show an implementation method that uses recursion, I thought I'd chuck one in. True, it's better using a loop but... some people just like recursion :) > Now I've made the following mess for myself: heh :) > def get_number(): > rawNum=raw_input("Enter a number between 0 and 10,000: ") > > try: > num_int = string.atoi(rawNum) > if (0 > num_int) or (num_int > 10000): > print 'Sorry, that number is not between 0 and 10000' > rawNum = get_number() # lest the value is lost in the wicked maze of recursion :) > > > except ValueError: > print "Try again. We need an integer between 0 and 10,000" > get_number() > > return rawNum > > <...> > > Here's what I don't understand: get_number() is called (function A) and > assigns a raw input value to rawNum. When rawNum fails the "string.atoi" > test, the function calls itself again (function B), assinging a new value to > rawNum which does not get passed to the function A when the function B > terminates. How do I (re)write the code so that function B passes the > correct value to function A? > Your code looks all well and good, but has a pretty major problem. When you recursively call get_number you aren't storing the value - something like 'result = get_number()' is needed. When you do this, you also need to declare result (again, simple as 'result = None') and modify the return statement. So, only really one change but the new incarnation would be... def get_number(): rawNum=raw_input("Enter a number between 0 and 10,000: ") try: result = None # don't want an unbound var error... num_int = int(rawNum) if (0 > num_int) or (num_int > 10000): print 'Sorry, that number is not between 0 and 10000' result = get_number() # lest the value is lost in the wicked maze of recursion :) except ValueError: print "Try again. We need an integer between 0 and 10,000" result = get_number() # ditto if result: return result else: return rawNum > Should I even bother or just re-write the body of the if-test to re-prompt > without a recursive call? > It's not too much trouble to correctly recursify it, esp if you've already built the function. Anywho, have fun :) Glen From Keila - Curitiba - Pr" Olá! Veja meu site pessoal no "Tripod.com.br". Basta clicar no endereço abaixo. GARANTO SER SUI-GENERIS - CLIQUE ABAIXO: http://pastorinha.tripod.com.br/seminarista Mais de 61.000 internautas visitaram a PG., existe 7 Álbuns: Se você quiser, por favor, indique minha Home Page, a outros Internautas. Mais detalhes, se comunique, passe um e-mail, que responderei brevemente. Dentro da Home Page, ao lado das fotos, você poderá saber muito mais sobre mim! Obrigada. e-mail: pastorinha@ieg.com.br Beijos:- Keila - Curitiba - Pr - Podes falar comigo, direto dela. Brevemente uma Carta Aberta. http://pastorinha.tripod.com.br/seminarista "Esta mensagem é enviada com a complacência da nova legislação sobre correio eletrônico, Seção 301, Parágrafo (a) (2) (c) Decreto S. 1618, Título Terceiro aprovado pelo "105º Congresso Base das Normativas Internacionais sobre o SPAM". Este E-mail não poderá ser considerado SPAM quando incluir uma forma de ser removido. Para ser removido de futuros correios, simplesmente responda indicando no Assunto: REMOVER" From shalehperry@home.com Sun Oct 14 03:46:42 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Sat, 13 Oct 2001 19:46:42 -0700 (PDT) Subject: [Tutor] Now I have a variable-passing problem! In-Reply-To: <006101c15456$ba4529a0$c1a616ca@ACE> Message-ID: >> Should I even bother or just re-write the body of the if-test to re-prompt >> without a recursive call? >> > > It's not too much trouble to correctly recursify it, esp if you've already > built the function. > the problem with recursion is the case where the user (or whatever) just keeps sending bad input. Then the recursion just gets deeper and deeper, python will eventually hiccup or segfault. Also recursion is more expensive than the loop, especially if the user/input has many incorrect entries. From wheelege@tsn.cc Sun Oct 14 05:31:39 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Sun, 14 Oct 2001 14:31:39 +1000 Subject: [Tutor] Now I have a variable-passing problem! References: Message-ID: <008b01c15469$1e9ba2a0$c1a616ca@ACE> > >> Should I even bother or just re-write the body of the if-test to re-prompt > >> without a recursive call? > >> > > > > It's not too much trouble to correctly recursify it, esp if you've already > > built the function. > > > > the problem with recursion is the case where the user (or whatever) just keeps > sending bad input. Then the recursion just gets deeper and deeper, python will > eventually hiccup or segfault. Also recursion is more expensive than the loop, > especially if the user/input has many incorrect entries. > Right...I was only showing how to do it the recursive way for academic purposes - 'If we lived in this alternate universe where loops didn't exist, how would we implement it?' :) From urnerk@qwest.net Sun Oct 14 05:56:01 2001 From: urnerk@qwest.net (Kirby Urner) Date: Sat, 13 Oct 2001 21:56:01 -0700 Subject: [Tutor] Intro to CS (boolean.py) In-Reply-To: <4.2.0.58.20011013090449.00c02990@pop3.norton.antivirus> References: Message-ID: <4.2.0.58.20011013213544.00c4f5d0@pop3.norton.antivirus> Here's a simple boolean algebra module, for which "useless Python" I'll no doubt find many more capable versions (haven't checked yet). Still, I like this one because it includes a broad range of Python concepts in not-too-difficult form, namely: * a simple class: the Bool class does little more than override the behavior of __invert__ for integers, so instead of getting two's complement, I get the logical negation, i.e. I say '~a' instead of 'not a'. * a regular expression: really basic, but used to find all occurances of a single letter variable, and replace it with ~variable. This version only allows up to four variables a-d. * plenty of string manipulation, which is the nuts and bolts of a lot of programming * an example of eval() with a local namespace Here's how it looks, used in shell mode: >>> reload(boolean) >>> boolean.truth(1,'~a') a | ~a ==|=== 0 | 1 1 | 0 >>> expr = "(a & ~b) | c" >>> boolean.truth(3,expr) a b c | (a & ~b) | c ======|============= 0 0 0 | 0 0 0 1 | 1 0 1 0 | 0 0 1 1 | 1 1 0 0 | 1 1 0 1 | 1 1 1 0 | 0 1 1 1 | 1 >>> newexpr = boolean.demorgan(expr) >>> newexpr '~(((~a) | ~(~b)) & (~c))' >>> boolean.truth(3,newexpr) a b c | ~(((~a) | ~(~b)) & (~c)) ======|========================= 0 0 0 | 0 0 0 1 | 1 0 1 0 | 0 0 1 1 | 1 1 0 0 | 1 1 0 1 | 1 1 1 0 | 0 1 1 1 | 1 As an intro to computer science module, it's got some other key stuff too, in addition to exercising the above features of Python (which features are characteristic of many other languages). It's got decimal to binary conversion... >>> from boolean import bin >>> bin(10) '1010' >>> bin(100) '1100100' >>> bin(3242034) '1100010111100000110010' And it's got this DeMorgan's equivalence relation, whereby you can express the same logical expression in two different ways. CS students know what I'm talking about. That being said, I'm sure the code could be enchanced/improved, features added and so on (I'm working on an improvement or two right now). So, have at it... Kirby ===== """ Simple boolean algebra module by Kirby Urner, Oct 13, 2001 """ from string import replace, center from re import sub class Bool: """ Intialize w/ 1 or 0: a,b = Bool(1), Bool(0) Example expressions: a&b, a|b, ~a (note: ~ for negation) returns a Bool """ def __init__(self,val): if not (val==0 or val==1): raise ValueError,"Must be 1 or 0" self.value = val def __invert__(self): return Bool(not self.value) def __and__(self,other): return Bool(self.value & other.value) def __or__(self,other): return Bool(self.value | other.value) def __repr__(self): return repr(self.value) def demorgan(expr): """ Swap & with |, negate args, negate expression -- should have same truth table as original """ def negate(matchobj): t = matchobj.group(0) return '(~%s)' % t expr = replace(expr,'&','@') expr = replace(expr,'|','&') expr = replace(expr,'@','|') expr = sub('[a-d]',negate,expr) return "~("+expr+")" def bin(n): result = '' while 1: result = str(n%2)+result n = n//2 if not n: break return result def truth(n,expr): """ Generates truth table for n=1-4 variables a-d, for the passed boolean expression expr """ truth_table = [] locals = {} padding = n*'0' for i in range(2**n): digits = (padding + bin(i))[-n:] truth_table.append(tuple(digits)) print print " "+("%s "*n) % tuple('abcd')[:n] + "| " + expr print " "+"=="*n + "|=" + "="*len(expr) for row in truth_table: for i in range(n): locals['abcd'[i]]=Bool(int(row[i])) print " "+("%s "*n) % row + "| " + \ center(str(eval(expr,locals)),len(expr)) print ===== From rufmetal@home.com Sun Oct 14 07:09:03 2001 From: rufmetal@home.com (Chris Keelan) Date: Sun, 14 Oct 2001 01:09:03 -0500 Subject: [Tutor] Now I have a variable-passing problem! In-Reply-To: <006101c15456$ba4529a0$c1a616ca@ACE> References: <01101312030400.01555@tygesen> <006101c15456$ba4529a0$c1a616ca@ACE> Message-ID: <01101401090301.01744@tygesen> On Sat, 13 Oct 2001, Glen Wheeler wrote: > Your code looks all well and good, but has a pretty major problem. When > you recursively call get_number you aren't storing the value - something > like 'result = get_number()' is needed. That's what I thought. I also understand why recursion is a potentially BadThing[TM], at least in this situation. >When you do this, you also need to > declare result (again, simple as 'result = None') and modify the return > statement. So, only really one change but the new incarnation would be... > > def get_number(): > rawNum=raw_input("Enter a number between 0 and 10,000: ") > > try: > result = None # don't want an unbound var error... > num_int = int(rawNum) > if (0 > num_int) or (num_int > 10000): > print 'Sorry, that number is not between 0 and 10000' > result = get_number() # lest the value is lost in the wicked > maze of recursion :) > > except ValueError: > print "Try again. We need an integer between 0 and 10,000" > result = get_number() # ditto > > if result: > return result > else: > return rawNum > > > Should I even bother or just re-write the body of the if-test to > > re-prompt without a recursive call? > > It's not too much trouble to correctly recursify it, esp if you've > already built the function. This is good advice, but I think I agree (as you do) with Sean and Andrew's "loop" approach, which is the one I'm going to use. > > Anywho, have fun :) When I look up "fun" in the dictionary, the third entry says "see `Python' ", heh! Thanks again gang. If anyone is ever in the Toronto area, I'm buying the beer! - Chris From kaya4321@yahoo.com Sun Oct 14 10:27:21 2001 From: kaya4321@yahoo.com (necati kaya) Date: Sun, 14 Oct 2001 02:27:21 -0700 (PDT) Subject: [Tutor] seed & random !? Message-ID: <20011014092721.55396.qmail@web9207.mail.yahoo.com> Hi, I am trying to generate different new_list randomly in each step of the loop from original_list, but I can not. As the example; original_list=['1','2','3','4'] and my program produce those new_lists randomly, but ['4', '2', '3', '1'] ==> ['1', '4', '2', '3'] Both are same ['4', '2', '3', '1'] ==> ['3', '2', '1', '4'] ['2', '4', '3', '1'] I tried to use seed function, but it gave me all the same results. Do you have any suggestion to have different new_list which is generated from original_list in every step. Regards, umit Here is my code: from random import Random import random original_list=['1','2','3','4'] for j in range(0, 5): temp_list = original_list[:] new_list=[] for i in range(0, len(original_list)): # random.seed() #?????????????? choosen_item = random.choice(temp_list) new_list.append(choosen_item) temp_list.remove(choosen_item) print new_list print __________________________________________________ Do You Yahoo!? Make a great connection at Yahoo! Personals. http://personals.yahoo.com From samirdpatel@hotmail.com Sun Oct 14 10:28:55 2001 From: samirdpatel@hotmail.com (Samir Patel) Date: Sun, 14 Oct 2001 09:28:55 Subject: [Tutor] finding title tag in a link tag ?? Message-ID:
hi,
i am trying to save a list of links present a url which is given through command line.i am doing this to a certain depth and saving all this links in a universal list.
now my problem is that i want to get the titles present in that Achor tag e.g
 
<a href = "url" title = "i want this">or this</a>
 
so how can i get that and store that  with respective particular link.
following is the code which i have written and want to add adove stuff to it.....
 
import re
import sys
import urllib
from formatter import NullFormatter
from htmllib import HTMLParser
from string import find,lower
from urlparse import urljoin,urlparse
 
def findlinks(url):
   try:
       fp = urllib.urlopen(url)
  
   except IOError:
       return []              # return an empty list if we can't get a page
   results = []               # create an empty list to store results in
   
   p = HTMLParser(NullFormatter())
   p.feed(fp.read())
   return p.anchorlist    # return the list of lines which have a link
def scanpage(ser_name,url, depth, maxindent):
 
   linklist = findlinks(url)
   if maxindent == None:
       
 maxindent = depth
  
   indent = " " * (3*(maxindent - depth))  # this will let us progressively indent printouts from deeper levels
 
   print "%s   -> %s" % (indent, url)
  
   if depth > 0:
      
       for link in linklist:
          
    pars = urlparse(link)
   
    if pars[0] == 'https':
        print 'Secure site !! Cannot open ....skipped...'
        continue
   
    if find(lower(link),'mailto:') != -1:   # check if the link is a mailto tag
        continue
    if link[:4] != 'http' and link[0] == '/' :
     
      link = urljoin(url,link)
   
    if link[:4] != 'http'and link[0] != '/' :
      link = urljoin(url,link)
         
    global_list.append(link)
    serve = get_server(link)
   
    if select == '-L':
        if serve == ser_name or serve == None:
     scanpage(ser_name,link, depth - 1, maxindent)   #function is again called with individual url
    else:
        scanpage(ser_name,link, depth - 1, maxindent)
     
def get_server(input_url):
 
   try:
       server = re.split('//',input_url)
       server_name = re.split('/',server[1])
       return server_name[0] 
   except:
       return None    
try:         
   select = sys.argv[1]
except IndexError:
   print "Error!! Please give a valid argument"
   sys.exit()
get_depth = None
global_list = []
ser_name = None
if len(sys.argv) == 2:
 
   parsed = urlparse(select)
  
   if parsed[0] != 'http':
         print '---> Invalid URL !! URL should start with http://'  #checking if the url entered is a valid one
  sys.exit()
  
   scanpage(parsed[1],select,3,None)
elif select == '-d' or select == '-L':
   if select == '-d':
    
      try:
         get_depth = sys.argv[2]   
         input_url = sys.argv[3]
      except IndexError:
         print "Error!! Please give a valid argument"
         sys.exit()
    
      url_parsed = urlparse(input_url)
     
      if url_parsed[0] != 'http':
         print '---> Invalid URL !! URL should start with http://'  #checking if the url entered is a valid one
  sys.exit()
     
      print "You have selected the depth option\n"
      scanpage(url_parsed[1],input_url,int(get_depth),None)
  
  
   elif select == '-L':
  
      try:
         input_url = sys.argv[2]
      except IndexError:
         print "Error!! Please give a valid argument"
         sys.exit()
    
      url_parsed = urlparse(input_url)
      if url_parsed[0] != 'http':
         print '---> Invalid URL !! URL should start with http://'  #checking if the url entered is a valid one
  sys.exit()
  
      print "You have selected Local access option\n"
      scanpage(url_parsed[1],input_url,3,None)
else:
    print "Error !! Invalid argument"
    sys.exit() 
#print "global list",global_list 
 
#thanking you
 
#samir


Get your FREE download of MSN Explorer at http://explorer.msn.com
From ak@silmarill.org Sun Oct 14 10:38:14 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Sun, 14 Oct 2001 05:38:14 -0400 Subject: [Tutor] seed & random !? In-Reply-To: <20011014092721.55396.qmail@web9207.mail.yahoo.com> References: <20011014092721.55396.qmail@web9207.mail.yahoo.com> Message-ID: <20011014053814.A28032@sill.silmarill.org> On Sun, Oct 14, 2001 at 02:27:21AM -0700, necati kaya wrote: > Hi, > I am trying to generate different new_list randomly in > each step of the loop from original_list, but I can > not. As the example; > original_list=['1','2','3','4'] and my program produce > those new_lists randomly, but > > ['4', '2', '3', '1'] ==> > ['1', '4', '2', '3'] Both are same > ['4', '2', '3', '1'] ==> > ['3', '2', '1', '4'] > ['2', '4', '3', '1'] > > I tried to use seed function, but it gave me all the > same results. Do you have any suggestion to have > different new_list which is generated from > original_list in every step. If I understood right, you want to create random lists that have the same elements as a given list, but not in the same order.. if that's true, you can do this with my_list.shuffle: >>> from random import shuffle >>> l [3, 4, 2, 1] >>> from copy import copy >>> l2 = copy(l) >>> shuffle(l2) >>> l2 [2, 4, 3, 1] >>> l [3, 4, 2, 1] >>> for i in range(10): ... shuffle(l2) ... if l != l2: ... print l2 ... [3, 1, 4, 2] [1, 2, 4, 3] [4, 3, 2, 1] [2, 1, 4, 3] [1, 3, 4, 2] [4, 3, 2, 1] [2, 1, 4, 3] [3, 4, 1, 2] [4, 1, 2, 3] [2, 1, 4, 3] >>> l [3, 4, 2, 1] Instead of printing, you can append it to a list of random lists.. Hope that's what you wanted :P > Regards, > umit > > Here is my code: > > > from random import Random > import random > > original_list=['1','2','3','4'] > for j in range(0, 5): > temp_list = original_list[:] > new_list=[] > for i in range(0, len(original_list)): > # random.seed() > #?????????????? > choosen_item = random.choice(temp_list) > new_list.append(choosen_item) > temp_list.remove(choosen_item) > print new_list > print > > > __________________________________________________ > Do You Yahoo!? > Make a great connection at Yahoo! Personals. > http://personals.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From kaya4321@yahoo.com Sun Oct 14 11:45:52 2001 From: kaya4321@yahoo.com (necati kaya) Date: Sun, 14 Oct 2001 03:45:52 -0700 (PDT) Subject: [Tutor] seed & random !? In-Reply-To: <20011014053814.A28032@sill.silmarill.org> Message-ID: <20011014104552.25868.qmail@web9203.mail.yahoo.com> Thank you for your suggestion, but it is half of what I need: I want to create random lists that have the same elements as a given list, but not in the same order with original and also with previous generated lists. What you suggested is really useful for me to create the total number of permutations of original list, but it gives also previous generated list order: list_1 : ['1', '2', '3', '4'] 0 -> ['1', '4', '3', '2'] 1 -> ['4', '3', '2', '1'] 2 -> ['1', '3', '2', '4'] ___ 4 -> ['1', '3', '4', '2'] \ 6 -> ['2', '1', '3', '4'] \ Both are same !! 7 -> ['3', '1', '2', '4'] / 8 -> ['1', '3', '2', '4'] ___/ 9 -> ['4', '3', '2', '1'] ################################ from random import shuffle from copy import copy list_1 = ['1', '2', '3', '4'] list_2 = copy(list_1) print 'list_1 :', list_1 print for i in range(10): shuffle(list_2) if list_1 != list_2: print i,'->', list_2 ################################# Regards, umit --- Andrei Kulakov wrote: > On Sun, Oct 14, 2001 at 02:27:21AM -0700, necati > kaya wrote: > > Hi, > > I am trying to generate different new_list > randomly in > > each step of the loop from original_list, but I > can > > not. As the example; > > original_list=['1','2','3','4'] and my program > produce > > those new_lists randomly, but > > > > ['4', '2', '3', '1'] ==> > > ['1', '4', '2', '3'] Both are same > > ['4', '2', '3', '1'] ==> > > ['3', '2', '1', '4'] > > ['2', '4', '3', '1'] > > > > I tried to use seed function, but it gave me all > the > > same results. Do you have any suggestion to have > > different new_list which is generated from > > original_list in every step. > > If I understood right, you want to create random > lists that have the same > elements as a given list, but not in the same > order.. if that's true, you > can do this with my_list.shuffle: > > >>> from random import shuffle > >>> l > [3, 4, 2, 1] > >>> from copy import copy > >>> l2 = copy(l) > >>> shuffle(l2) > >>> l2 > [2, 4, 3, 1] > >>> l > [3, 4, 2, 1] > >>> for i in range(10): > ... shuffle(l2) > ... if l != l2: > ... print l2 > ... > [3, 1, 4, 2] > [1, 2, 4, 3] > [4, 3, 2, 1] > [2, 1, 4, 3] > [1, 3, 4, 2] > [4, 3, 2, 1] > [2, 1, 4, 3] > [3, 4, 1, 2] > [4, 1, 2, 3] > [2, 1, 4, 3] > >>> l > [3, 4, 2, 1] > > Instead of printing, you can append it to a list of > random lists.. > > Hope that's what you wanted :P > > > Regards, > > umit > > > > Here is my code: > > > > > > from random import Random > > import random > > > > original_list=['1','2','3','4'] > > for j in range(0, 5): > > temp_list = original_list[:] > > new_list=[] > > for i in range(0, len(original_list)): > > # random.seed() > > #?????????????? > > choosen_item = > random.choice(temp_list) > > new_list.append(choosen_item) > > temp_list.remove(choosen_item) > > print new_list > > print > > > > > > __________________________________________________ > > Do You Yahoo!? > > Make a great connection at Yahoo! Personals. > > http://personals.yahoo.com > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- > Cymbaline: intelligent learning mp3 player - python, > linux, console. > get it at: cy.silmarill.org > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor __________________________________________________ Do You Yahoo!? Make a great connection at Yahoo! Personals. http://personals.yahoo.com From ak@silmarill.org Sun Oct 14 11:55:53 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Sun, 14 Oct 2001 06:55:53 -0400 Subject: [Tutor] seed & random !? In-Reply-To: <20011014104552.25868.qmail@web9203.mail.yahoo.com> References: <20011014053814.A28032@sill.silmarill.org> <20011014104552.25868.qmail@web9203.mail.yahoo.com> Message-ID: <20011014065553.A29955@sill.silmarill.org> On Sun, Oct 14, 2001 at 03:45:52AM -0700, necati kaya wrote: > Thank you for your suggestion, but it is half of what > I need: > I want to create random lists that have the same > elements as a given list, but not in the same order > with original and also with previous generated lists. Oh.. okay then.. simply append them to a list of random lists and test if it's there or not.. see below. > > What you suggested is really useful for me to create > the total number of permutations of original list, but > it gives also previous generated list order: > > list_1 : ['1', '2', '3', '4'] > > 0 -> ['1', '4', '3', '2'] > 1 -> ['4', '3', '2', '1'] > 2 -> ['1', '3', '2', '4'] ___ > 4 -> ['1', '3', '4', '2'] \ > 6 -> ['2', '1', '3', '4'] \ Both are same !! > 7 -> ['3', '1', '2', '4'] / > 8 -> ['1', '3', '2', '4'] ___/ > 9 -> ['4', '3', '2', '1'] > > ################################ > from random import shuffle > from copy import copy > > list_1 = ['1', '2', '3', '4'] lists = [list_1] > list_2 = copy(list_1) > print 'list_1 :', list_1 > print > for i in range(10): > shuffle(list_2) if list_2 not in lists: l = copy(list_2) lists.append(l) But.. do you need *all* permutations? If so, there must be a more efficient and straightforward way to do this.. > > ################################# > > Regards, > umit > > > --- Andrei Kulakov wrote: > > On Sun, Oct 14, 2001 at 02:27:21AM -0700, necati > > kaya wrote: > > > Hi, > > > I am trying to generate different new_list > > randomly in > > > each step of the loop from original_list, but I > > can > > > not. As the example; > > > original_list=['1','2','3','4'] and my program > > produce > > > those new_lists randomly, but > > > > > > ['4', '2', '3', '1'] ==> > > > ['1', '4', '2', '3'] Both are same > > > ['4', '2', '3', '1'] ==> > > > ['3', '2', '1', '4'] > > > ['2', '4', '3', '1'] > > > > > > I tried to use seed function, but it gave me all > > the > > > same results. Do you have any suggestion to have > > > different new_list which is generated from > > > original_list in every step. > > > > If I understood right, you want to create random > > lists that have the same > > elements as a given list, but not in the same > > order.. if that's true, you > > can do this with my_list.shuffle: > > > > >>> from random import shuffle > > >>> l > > [3, 4, 2, 1] > > >>> from copy import copy > > >>> l2 = copy(l) > > >>> shuffle(l2) > > >>> l2 > > [2, 4, 3, 1] > > >>> l > > [3, 4, 2, 1] > > >>> for i in range(10): > > ... shuffle(l2) > > ... if l != l2: > > ... print l2 > > ... > > [3, 1, 4, 2] > > [1, 2, 4, 3] > > [4, 3, 2, 1] > > [2, 1, 4, 3] > > [1, 3, 4, 2] > > [4, 3, 2, 1] > > [2, 1, 4, 3] > > [3, 4, 1, 2] > > [4, 1, 2, 3] > > [2, 1, 4, 3] > > >>> l > > [3, 4, 2, 1] > > > > Instead of printing, you can append it to a list of > > random lists.. > > > > Hope that's what you wanted :P > > > > > Regards, > > > umit > > > > > > Here is my code: > > > > > > > > > from random import Random > > > import random > > > > > > original_list=['1','2','3','4'] > > > for j in range(0, 5): > > > temp_list = original_list[:] > > > new_list=[] > > > for i in range(0, len(original_list)): > > > # random.seed() > > > #?????????????? > > > choosen_item = > > random.choice(temp_list) > > > new_list.append(choosen_item) > > > temp_list.remove(choosen_item) > > > print new_list > > > print > > > > > > > > > __________________________________________________ > > > Do You Yahoo!? > > > Make a great connection at Yahoo! Personals. > > > http://personals.yahoo.com > > > > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > -- > > Cymbaline: intelligent learning mp3 player - python, > > linux, console. > > get it at: cy.silmarill.org > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > __________________________________________________ > Do You Yahoo!? > Make a great connection at Yahoo! Personals. > http://personals.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From rick@niof.net Sun Oct 14 14:14:32 2001 From: rick@niof.net (Rick Pasotto) Date: Sun, 14 Oct 2001 09:14:32 -0400 Subject: [Tutor] seed & random !? In-Reply-To: <20011014104552.25868.qmail@web9203.mail.yahoo.com> References: <20011014053814.A28032@sill.silmarill.org> <20011014104552.25868.qmail@web9203.mail.yahoo.com> Message-ID: <20011014091432.B28050@tc.niof.net> On Sun, Oct 14, 2001 at 03:45:52AM -0700, necati kaya wrote: > Thank you for your suggestion, but it is half of what > I need: > I want to create random lists that have the same > elements as a given list, but not in the same order > with original and also with previous generated lists. The additional restrictions mean you are not really looking for *random* lists. Truly random lists might very well match previous lists. -- [The socialists say that society, left to itself, heads inevitably for destruction because its instincts are perverse. They demand the power to stop mankind from sliding down this fatal declivity and to impose a better direction on it. If, then, they have received from heaven intelligence and virtues that place them beyond and above mankind, let them show their credentials. They want to be shepherds, and they want us to be their sheep. This arrangement presupposes in them a natural superiority, a claim that we have every right to require them to establish before we go any further. -- Frédéric Bastiat (1801-1850) Rick Pasotto rickp@telocity.com http://www.niof.net From shalehperry@home.com Sun Oct 14 17:40:22 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Sun, 14 Oct 2001 09:40:22 -0700 (PDT) Subject: html in email RE: [Tutor] finding title tag in a link tag ?? In-Reply-To: Message-ID: ok friends, let's not send people html email to people who did not ask for it. To some of us that last mail looked like line noise. From alan.gauld@bt.com Sun Oct 14 18:24:45 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 14 Oct 2001 18:24:45 +0100 Subject: [Tutor] Now I have a variable-passing problem! Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFE9@mbtlipnt02.btlabs.bt.co.uk> > you recursively call get_number you aren't storing the value > like 'result = get_number()' is needed. Or just use rawNum... You could also change the logic of the range check to simplify a little more and by raising a ValueError keep all the error handling in one place.. def get_number(): rawNum=raw_input("Enter a number between 0 and 10,000: ") try: num_int = int(rawNum) if 0 < num_int < 10000: return rawNum else: raise ValueError except ValueError: print "Sorry please try again." return get_number() Since get_number only ever returns a valid number there's no need to have an intermediate 'result'. Just nit-picking... Alan g. From m_konermann@gmx.de Sun Oct 14 19:15:59 2001 From: m_konermann@gmx.de (Marcus Konermann) Date: Sun, 14 Oct 2001 20:15:59 +0200 Subject: [Tutor] Extending Python with C++ by using SWIG Message-ID: <3BC9D65F.60504@gmx.de> This is a multi-part message in MIME format. --------------090406070505010807060407 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 8bit Hallo ! I´m developing a project excisting of a Tkinter User Interface and C++ and some Python Code. So the first Step i want to do is to extend the Tkinter User Interface with the C++ Code by using SWIG and for me it´s the first time working with SWIG (but by the way i think it´s for me the fastest way to integrate the C++ Code in Python). I´m working under win2000 with pywin and i´m using the VC++ 6.0 Compiler. I hope that i installed the SWIG Wrapper correct under VC++ 6.0, but after building the project the following mistakes are produced from the Compiler: SWIG Generating wrappers for Python ..\basisfile.i : Line 10. Warning. Use of C++ Reference detected. Use the -c++ option. Kompilierung läuft... basisfile.cpp basisfile.obj : error LNK2001: Nichtaufgeloestes externes Symbol "public: __thiscallstring::~string(void)"(??1string@@QAE@XZ) basisfile.obj : error LNK2001: Nichtaufgeloestes externes Symbol "public: __thiscall string::string(void)" (??0string@@QAE@XZ) basisfile.obj : error LNK2001: Nichtaufgeloestes externes Symbol "public: void __thiscall string::clean(void)" (?clean@string@@QAEXXZ) ... Perhaps there´s a problem with classes in SWIG and i have to write additional Information for the SWIG Wrapper in the basisfile.i File. So, it would be very good for me if anyone already worked with SWIG and can help me. Thanks a lot Marcus --------------090406070505010807060407 Content-Type: text/plain; name="basisfile.cpp" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="basisfile.cpp" #include "basisfile.h" filetext::filetext () { tlln = 0; tfln = 0; variable_pointer = NULL; next = NULL; } filetext::~filetext () { clean (); } void filetext::clean () { clean (this); } void filetext::clean (struct filetext *ft) { if (ft) { if (ft->next) { clean (ft->next); ft->next = NULL; } variable_pointer = NULL; text.clean (); parameter_text.clean (); } } basisfile::basisfile () { filename = NULL; text = NULL; } basisfile::basisfile (struct string &fn) { filename = new struct string; filename->copy (fn); text = NULL; } basisfile::basisfile (char *fn) { init (fn); } basisfile::~basisfile () { clean (); } void basisfile::init (char *fn) { filename = new struct string; filename->copy (fn); text = NULL; } void basisfile::clean () { if (filename) { delete filename; filename = NULL; } if (text) { delete text; text = NULL; } } int basisfile::readfile () { if (!filename->size) { printf ("basisfile::readfile:\n No filename to read specified.\n"); return 1; } /* initialize text-pointer */ text = new struct filetext; /* Copy complete input file to text */ text->tfln = 1; if ((text->tlln = text->text.filereadc (*filename, '\n')) < 0) { printf ("basisfile::readfile ():\n "); strprint (*filename, "Error while reading file `", "'.\n"); return 1; } return 0; } int basisfile::writefile (string &otherfilename, char *mode) { struct filetext *help = this->text; if ( (*mode != 'a') && (*mode != 'w') ) { printf ("basisfile::writefile:\n Invalid mode %s ", mode); strprint (otherfilename, "for writing to file `", "'.\n"); return 1; } FILE *out = otherfilename.fileopen (mode); if (out) while (help != NULL) { if (help->text.size) help->text.filewrite (out); if (help->parameter_text.size) help->parameter_text.filewrite (out); help = help->next; } else { strprint (otherfilename, "basisfile::writefile:\n Unable to open file `", "'"); printf (" with mode %s.\n", mode); return 2; } while (help != NULL) { if (help->text.size) help->text.filewrite (otherfilename, "a"); if (help->parameter_text.size) help->parameter_text.filewrite (otherfilename, "a"); help = help->next; } return 0; } int basisfile::writefile (char *mode) { struct filetext *help = this->text; if ( (*mode != 'a') && (*mode != 'w') ) { printf ("basisfile::writefile:\n Invalid mode %s ", mode); strprint (*filename, "for writing to file `", "'.\n"); return 1; } FILE *out = filename->fileopen (mode); if (out) { while (help != NULL) { if (help->text.size) help->text.filewrite (out); if (help->parameter_text.size) help->parameter_text.filewrite (out); help = help->next; } fclose (out); } else { strprint (*filename, "basisfile::writefile:\n Unable to open file `", "'"); printf (" with mode %s.\n", mode); return 2; } // while (help != NULL) { // if (help->text.size) // help->text.filewrite (*filename, "a"); // if (help->parameter_text.size) // help->parameter_text.filewrite (*filename, "a"); // help = help->next; // } return 0; } int basisfile::build (struct variablelist *variable) { struct filetext *help; int splitswitch; /* Look for specified variable */ while (variable) { help = this->text; /* search all parts of basisfile (except in parameter-text-parts) */ while (help) { /* search in text */ if (variable->linenumber <= help->tlln) { /* split text */ if ( split (&help, variable) ) { printf ("Error while splitting basisfile structure.\n"); return 1; } else /* parameter found */ help = NULL; } else { /* nothing found */ help = help->next; } } /* found parameter? */ if (!variable->text) { printf ("Couldn't find parameter number %d.\n", variable->number); printf ("Probably line number %d exceeds number of lines of file.\n", variable->linenumber); return 2; } /* look at next one */ variable = variable->next; } return 0; } int basisfile::split (struct filetext **text, struct variablelist *variable, int separators) { int line = (*text)->tfln; int linepos = 0, prepos = 0, pastpos; int original_size = (*text)->text.size; int original_tlln = (*text)->tlln; string help, dummy; int next_line_offset; struct filetext *hft = NULL; /* check text */ if (!text || !(*text)) { printf ("basisfile::split:\n Empty filetext structure. Aborting.\n"); return 100; } /* check linenumber and position */ if (variable->linenumber < 1) { printf ("basisfile::split:\n Invalid linenumber %d.\n", variable->linenumber); return 99; } if (variable->position < 0) { printf ("basisfile::split:\n Invalid position %d.\n", variable->position); return 99; } /* find right line */ while (line < variable->linenumber) { linepos += (*text)->text.string_complement_span("\n", linepos) + 1; line++; } next_line_offset = (*text)->text.string_complement_span("\n", linepos) + 1; /* if "\n" was not found, next_line_offset is position of "\0". Since this character is not meant to be copied to help, we must decrease next_line_offset by 1 in this case. */ if (next_line_offset+linepos == (*text)->text.size) help.ncopy ((*text)->text, next_line_offset-1, linepos); else help.ncopy ((*text)->text, next_line_offset, linepos); /* find beginning position of parameter-text in line */ while (separators < variable->position) { /* if not found */ if (!(help.string_string(dummy, variable->preseparator, prepos+1))) { /* Does line in question continue with next struct? */ if ( ((*text)->next) && ((*text)->next->tfln == line) ) return (split ( &((*text)->next), variable, separators)); else { printf("Problem in line no. %d:\n", line); printf(" Can not find more than %d", separators); strprint (variable->preseparator, " preseparators `", "'.\n"); printf(" Should have found %d.\n", variable->position); strprint (help, "Text of the line under consideration:\n \"", "\"\n"); return 1; } } prepos = help.size - dummy.size; separators++; } /* if no separators were meant to be found, dummy would not contain the string continuing with guessed variable-text start: dummy would be empty. */ if (!separators) dummy.copy (help); /* find ending position of parameter-text in line */ if (!variable->pastseparator.size) { printf("Problem with specification of variable no. %d:\n", variable->number); printf(" pastseparatpor is empty.\n"); return 2; } else if (!(help.string_string(dummy, variable->pastseparator, help.size-dummy.size + variable->preseparator.size - 1))) { printf("Problem in line no. %d:\n", line); printf(" Can not find"); strprint (variable->pastseparator, " pastseparator `", "' after "); printf ("%d. ", separators); strprint(variable->preseparator, "presaparator `", "'.\n"); strprint (help, "Text of the line under consideration:\n \"", "\"\n"); return 3; } pastpos = linepos + help.size - dummy.size; /* set adequat positions of beginning of parameter_text */ prepos += linepos + variable->preseparator.size - 1; /* save whole text */ dummy.copy ((*text)->text); /* copy non-parameter-text to text */ (*text)->text.ncopy (dummy, prepos); /* breaking line no. $line means, that text last line number is $line now. */ (*text)->tlln = line; /* Are we dealing with a line already splitted into text and paramter_text? Then save parameter_text and variable_pointer and take care of the variable-pointer to this old parameter_text. */ if ((*text)->parameter_text.size) { /* create new basisfile-node */ hft = new struct filetext; /* save parameter_text there. */ hft->parameter_text.copy ((*text)->parameter_text); /* save variable_pointer, too */ hft->variable_pointer = (*text)->variable_pointer; /* redirect variablelist-pointer to new location of old parameter_text. */ hft->variable_pointer->text = hft; } /* is some original text left behind new parameter_text? Save it! */ if (pastpos < original_size) { /* create new basisfile-node, if not done already */ if (!hft) hft = new struct filetext; /* save rest of the text in new node, too */ hft->text.ncopy (dummy, original_size-pastpos-1, pastpos); } /* copy parameter-text to parameter_text */ (*text)->parameter_text.ncopy (dummy, pastpos-prepos, prepos); /* link pointer of variable to according parameter_text and backlink pointer of *text to that same variable pointer. */ variable->text = (*text); (*text)->variable_pointer = variable; /* set adequat line numbers for new node and link it to the structure, if new node exists. */ if (hft) { /* text last line number is last line number of original text. */ hft->tlln = original_tlln; /* if parameter_text does not include '\n' of original line, new text first line number is just the number of the breaked line ($line). Otherwise new tfln is number of next line. */ if ((*text)->parameter_text.string_character ('\n')) hft->tfln = line+1; else hft->tfln = line; /* link new node to structure. aehm?? Take care of pointer of variable struct pointing to text->next. */ hft->next = (*text)->next; //hbf->next->variable_pointer->text = &hbf; (*text)->next = hft; } return 0; } int vl2pt (struct variablelist *vl) { while (vl) { if (vl->text) { if (vl->text->parameter_text.copy (vl->x_now)) { printf ("vl2pt:\n "); printf ("Error while copying x_now to paramter text.\n"); return 1; } } else { printf ("vl2pt:\n "); printf ("Cannot find paramter text for variable no. %d.\n", vl->number); return 2; } vl = vl->next; } return 0; } void print (struct filetext *ft) { while (ft) { printf ("tfln = %d\ttlln = %d\n", ft->tfln, ft->tlln); printf ("variablen_pointer->nummer = "); if (ft->variable_pointer) printf("%d\n", ft->variable_pointer->number); else printf("\n"); strprint (ft->text, "text:\n `", "'\n"); strprint (ft->parameter_text, "parameter_text: `", "'\n"); ft = ft->next; } } --------------090406070505010807060407 Content-Type: text/plain; name="basisfile.h" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="basisfile.h" #ifndef BASISFILE_H #define BASISFILE_H #include "safe_string.h" #include "variable.h" struct filetext { filetext (); ~filetext (); void clean (struct filetext *ft); void clean (); struct string text; struct string parameter_text; /* text first line number */ int tfln; /* text last line number */ int tlln; /* pointer to the variable-struct, which points to this text-struct. */ struct variablelist *variable_pointer; struct filetext *next; }; struct basisfile { basisfile (); basisfile (struct string &fn); basisfile (char *fn); ~basisfile (); void init (char *fn); void clean (); struct filetext *text; struct string *filename; int readfile (); /* write this.text and this.parameter_text to file 'filename'. writefile walks through from this to last element of next-pointer and writes first text and then parameter_text to the file. The file is opened once in mode 'mode'. Values of mode are meant to be "w"- or "a"-modes according to the fopen()-function. */ int writefile (struct string &filename, char *mode = "w"); int writefile (char *mode = "w"); int build (struct variablelist *variable); /* searches parameter_text specified in 'variable' in text of 'text'. If found, the text of 'text' is split into 'text' and 'parameter_text' and in case some text of the line is left, a new node is inserted into 'text'. In case of **text contains a splitted line, split will call itself recursively in order to search the whole line. The text-pointer of *variable is set to the node of **text containing the parametertext belonging to variable. How is parameter_text searched for? It is searched for the line variable->linenumber. variable->preseparator and variable->pastseparator gives the text left and right from the searched parameter_text. variable->position gives the number of preseparator sets which must be found before parameter_text. If variable->position is 0, variable->preseparator is ignored and it is assumed, that the parameter_text starts at the beginning of the line. If enough preseparators are found, the pastseparator will be searched for. An empty pastseparator will lead to an error, if the file is continuing after the parameter_text. A pastseparator not found, too. Return value is 0, if everything is fine, > 0 if an error occured. */ int split (struct filetext **text, struct variablelist *variable, int separators = 0); }; /* Copys x_now of variables to their parameter_texts */ int vl2pt (struct variablelist *vl); void print (struct filetext *ft); #endif --------------090406070505010807060407 Content-Type: text/plain; name="basisfile.i" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="basisfile.i" %module mybasisfile %{ #include "basisfile.h" %} extern filetext (); extern void clean (); extern basisfile (); extern void init (char *fn); extern int readfile (); extern int writefile (string &otherfilename, char *mode); extern int build (struct variablelist *variable); extern int split (struct filetext **text, struct variablelist *variable,int separators); extern int vl2pt (struct variablelist *vl); extern void print (struct filetext *ft); --------------090406070505010807060407-- From dyoo@hkn.eecs.berkeley.edu Mon Oct 15 01:17:59 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 14 Oct 2001 17:17:59 -0700 (PDT) Subject: [Tutor] seed & random !? [calling random.seed() more than once] In-Reply-To: <20011014092721.55396.qmail@web9207.mail.yahoo.com> Message-ID: On Sun, 14 Oct 2001, necati kaya wrote: > I tried to use seed function, but it gave me all the same results. Do We really don't get truly random numbers out of the 'random' module: what we get are "pseudorandom" numbers: that is, these numbers look random enough to be useful. These pseudorandom numbers are completely determined by a math formula that starts off with a seed value. We can almost think of it as shaking a hat filled with slips of paper, where the seed tells Python exactly how to shake the hat. Given a seed number, the random number generator will give a pseudorandom-looking sequence. But here's where the analogy to hat shaking in the real world breaks: if we start off the generator with the same seed, we get back the same random sequence! Take a look: ### >>> random.seed(42) >>> random.random(), random.random(), random.random() (0.25420336316883324, 0.46884405296716114, 0.19540525690312815) >>> random.seed(42) >>> random.random(), random.random(), random.random() (0.25420336316883324, 0.46884405296716114, 0.19540525690312815) ### So it's not quite random: everything depends on the initial seed value. This pseudorandomness can actually be a good thing: scientists often use pseudorandom numbers in modeling a natural system. They do need "random" looking numbers, but they also need to be able to reproduce their results, to show other scientists what they've done. By using a pseudorandom generator, scientists can get "randomness" and eat their cake too. Let's go back to your observation: > I tried to use seed function, but it gave me all the same results. Do If we call seed() without an initial seeding value, Python will seed our random number generator with the system clock. However, the system clock only has millisecond precision, so if we call seed() too quickly... ### >>> for i in range(5): ... random.seed() ... print random.random(), random.random(), random.random() ... 0.568006638742 0.223572689753 0.61370495775 0.573655982955 0.189610550271 0.806179106218 0.573655982955 0.189610550271 0.806179106218 0.573655982955 0.189610550271 0.806179106218 0.573655982955 0.189610550271 0.806179106218 ### Notice that the first set of numbers is different from the last five: that's evidence that the system clock "ticked" once at that moment. Still, the above shows that calling seed() too quickly will break the "randomness" of our random number generator. The solution to this mess? Don't call seed(). *grin* But seriously, Python does this for you already when it starts up, and in truth, seed() should only be called, at most, once in a program. If you have more questions, please feel free to ask! From tmbrau00@centre.edu Mon Oct 15 00:38:27 2001 From: tmbrau00@centre.edu (Timothy M. Brauch) Date: Sun, 14 Oct 2001 19:38:27 -0400 (EDT) Subject: [Tutor] Removing characters Message-ID: <2355.10.4.1.31.1003102707.squirrel@titan.centre.edu> I know there must a simple way to open a file and remove all the end of line characters and/or carriage returns. However, I can't seem to get it to work right. Any help? - Tim From urnerk@qwest.net Mon Oct 15 01:37:35 2001 From: urnerk@qwest.net (Kirby Urner) Date: Sun, 14 Oct 2001 17:37:35 -0700 Subject: [Tutor] seed & random !? In-Reply-To: <20011014065553.A29955@sill.silmarill.org> References: <20011014104552.25868.qmail@web9203.mail.yahoo.com> <20011014053814.A28032@sill.silmarill.org> <20011014104552.25868.qmail@web9203.mail.yahoo.com> Message-ID: <4.2.0.58.20011014173504.00c554e0@pop3.norton.antivirus> At 06:55 AM 10/14/2001 -0400, Andrei Kulakov wrote: >But.. do you need *all* permutations? If so, there must be a more >efficient and straightforward way to do this.. Indeed. Below is a function that takes a list of characters and returns all unique permutations thereof: def perm(set): """ Return all permutations of a set. Thanks to Daniel Ajoy for sharing his Logo version with me. """ if len(set)==0: return [] if len(set)==1: return set answ = [] for i in range(len(set)): base = [set[0]] rest = set[1:] answ = answ + [base + list(i) for i in perm(rest)] set = [set[-1]]+set[:-1] return answ >>> perm(['1','2','3']) [['1', '2', '3'], ['1', '3', '2'], ['3', '1', '2'], ['3', '2', '1'], ['2', '3', '1'], ['2', '1', '3']] >>> perm(['1','2','3','4']) [['1', '2', '3', '4'], ['1', '2', '4', '3'], ['1', '4', '2', '3'], ['1', '4', '3', '2'], ['1', '3', '4', '2'], ['1', '3', '2', '4'], ['4', '1', '2', '3'], ['4', '1', '3', '2'], ['4', '3', '1', '2'], ['4', '3', '2', '1'], ['4', '2', '3', '1'], ['4', '2', '1', '3'], ['3', '4', '1', '2'], ['3', '4', '2', '1'], ['3', '2', '4', '1'], ['3', '2', '1', '4'], ['3', '1', '2', '4'], ['3', '1', '4', '2'], ['2', '3', '4', '1'], ['2', '3', '1', '4'], ['2', '1', '3', '4'], ['2', '1', '4', '3'], ['2', '4', '1', '3'], ['2', '4', '3', '1']] I use it in my simplematrix module as part of what's needed to get the determinant of a matrix. Nothing random about it though. Kirby From dyoo@hkn.eecs.berkeley.edu Mon Oct 15 01:39:30 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 14 Oct 2001 17:39:30 -0700 (PDT) Subject: [Tutor] Intro to CS (boolean.py) In-Reply-To: <4.2.0.58.20011013213544.00c4f5d0@pop3.norton.antivirus> Message-ID: Hi Kirby, I've written a small "propositional logic" parser class that you might find useful: http://hkn.eecs.berkeley.edu/~dyoo/python/propositions/ I wrote it as an experiment with the Spark parser-generator a month ago. I haven't been working on it for a while now, and you're welcome to use the parser if it's useful for you. Here's a small sample of what it does: ### [dyoo@tesuque propositions-0.2]$ python parser.py This is a small test of the propositional parser. Enter propositional phrases at the prompt. To quit, type "quit" at the prompt. Examples of some phrases: jack and jill rock and rolling implies not moss [ParserTest] >>> a and not b or c or[and[a, not[b]], c] ### The parser tries to be nice by allowing both English and "C"-ish syntax, and sticks with precedence rules to reduce the number of parentheses needed to disambiguate the expressions. I actually have an updated version 0.3 on my laptop that should work better than what's on the web site, and I'll put it up tonight when I get the chance. (Version 0.2 is actually a little broken: it has a logic bug that I should investigate.) Hope this helps! From dyoo@hkn.eecs.berkeley.edu Mon Oct 15 02:05:24 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 14 Oct 2001 18:05:24 -0700 (PDT) Subject: [Tutor] Removing characters In-Reply-To: <2355.10.4.1.31.1003102707.squirrel@titan.centre.edu> Message-ID: On Sun, 14 Oct 2001, Timothy M. Brauch wrote: > I know there must a simple way to open a file and remove all the end > of line characters and/or carriage returns. However, I can't seem to > get it to work right. Any help? What sort of problems are you running into? If you can show us, we might be able to spot the bug that's causing problems. I do have a script below that will do the job, below the spoiler space. Hope this helps! *** Spoiler space below *** """trim_file.py --- Removes all end of line characters and carriage returns in a file, and moves the original into a backup file, just in case things go horribly wrong. Danny Yoo (dyoo@hkn.eecs.berkeley.edu) """ import sys, os, time def trimFile(filename): """Trims the newlines and carriage returns out of a file.""" contents = readContents(filename) contents = replaceWeirdCharacters(contents) writeContents(filename, contents) def readContents(filename): """Returns the contents of a file.""" return open(filename).read() def writeContents(filename, contents): """Writes out the contents to filename, and backs things up just in case bad things happen.""" os.rename(filename, filename + "-backup." + time.strftime("%m-%d-%Y")) out = open(filename, "w") out.write(contents) out.flush() out.close() def replaceWeirdCharacters(contents): """Removes newlines and carriage returns from a string, and returns this cleaned-up string to the user. Note: this uses Python 2.1 string methods: it might be better to use the string.replace() function instead for compatibility.""" return contents.replace("\n", "").replace("\r", "") if __name__ == '__main__': for filename in sys.argv[1:]: trimFile(filename) From urnerk@qwest.net Mon Oct 15 05:16:50 2001 From: urnerk@qwest.net (Kirby Urner) Date: Sun, 14 Oct 2001 21:16:50 -0700 Subject: [Tutor] Intro to CS (boolean.py) In-Reply-To: References: <4.2.0.58.20011013213544.00c4f5d0@pop3.norton.antivirus> Message-ID: <4.2.0.58.20011014211527.00c59570@pop3.norton.antivirus> At 05:39 PM 10/14/2001 -0700, Danny Yoo wrote: >Hi Kirby, > >I've written a small "propositional logic" parser class that you might >find useful: > > http://hkn.eecs.berkeley.edu/~dyoo/python/propositions/ > >I wrote it as an experiment with the Spark parser-generator a month ago. I >haven't been working on it for a while now, and you're welcome to use the >parser if it's useful for you. Impressive stuff Danny, as well as your plans for future features :-D. I don't see 0.3 up yet, but this is a thread I'd like to track. There could be some fun curriculum written around here. Kirby From sampatel@cs.rmit.edu.au Mon Oct 15 07:05:42 2001 From: sampatel@cs.rmit.edu.au (Samir Patel) Date: Mon, 15 Oct 2001 16:05:42 +1000 (EST) Subject: [Tutor] finding title tag Message-ID: hi, i have written a program which takes in the url at command line argument and finds the links present in that particular web page and this continues to a depth of 3 or more..... i store this links in a universal list ..now my problem is that i want to find if there's any title tag present in this link e.g or this if there's title tag then i want to store the value of this corresponding to the link..... following is the code which i have written and i want to extend this code .... import re import sys import urllib from formatter import NullFormatter from htmllib import HTMLParser from string import find,lower from urlparse import urljoin,urlparse def findlinks(url): try: fp = urllib.urlopen(url) except IOError: return [] # return an empty list if we can't get a page results = [] # create an empty list to store results in p = HTMLParser(NullFormatter()) p.feed(fp.read()) return p.anchorlist # return the list of lines which have a link def scanpage(ser_name,url, depth, maxindent): linklist = findlinks(url) if maxindent == None: maxindent = depth indent = " " * (3*(maxindent - depth)) # this will let us progressively indent printouts from deeper levels print "%s -> %s" % (indent, url) if depth > 0: for link in linklist: pars = urlparse(link) if pars[0] == 'https': print 'Secure site !! Cannot open ....skipped...' continue if find(lower(link),'mailto:') != -1: # check if the link is a mailto tag continue if link[:4] != 'http' and link[0] == '/' : link = urljoin(url,link) if link[:4] != 'http'and link[0] != '/' : link = urljoin(url,link) global_list.append(link) serve = get_server(link) if select == '-L': if serve == ser_name or serve == None: scanpage(ser_name,link, depth - 1, maxindent) #function is again called with individual url else: scanpage(ser_name,link, depth - 1, maxindent) def get_server(input_url): try: server = re.split('//',input_url) server_name = re.split('/',server[1]) return server_name[0] except: return None try: select = sys.argv[1] except IndexError: print "Error!! Please give a valid argument" sys.exit() get_depth = None global_list = [] ser_name = None if len(sys.argv) == 2: parsed = urlparse(select) if parsed[0] != 'http': print '---> Invalid URL !! URL should start with http://' #checking if the url entered is a valid one sys.exit() scanpage(parsed[1],select,3,None) elif select == '-d' or select == '-L': if select == '-d': try: get_depth = sys.argv[2] input_url = sys.argv[3] except IndexError: print "Error!! Please give a valid argument" sys.exit() url_parsed = urlparse(input_url) if url_parsed[0] != 'http': print '---> Invalid URL !! URL should start with http://' #checking if the url entered is a valid one sys.exit() print "You have selected the depth option\n" scanpage(url_parsed[1],input_url,int(get_depth),None) elif select == '-L': try: input_url = sys.argv[2] except IndexError: print "Error!! Please give a valid argument" sys.exit() url_parsed = urlparse(input_url) if url_parsed[0] != 'http': print '---> Invalid URL !! URL should start with http://' #checking if the url entered is a valid one sys.exit() print "You have selected Local access option\n" scanpage(url_parsed[1],input_url,3,None) else: print "Error !! Invalid argument" sys.exit() #print "global list",global_list #thanking you #samir From nhytro-python@web.de Mon Oct 15 11:08:46 2001 From: nhytro-python@web.de (Sharriff Aina) Date: Mon, 15 Oct 2001 12:08:46 +0200 Subject: [Tutor] Tkinter File browswer Message-ID: <200110151008.f9FA8ku09421@mailgate5.cinetic.de> Could someone show me how to code a file browser widget with Tkinter and Pmw? Thanks _______________________________________________________________________ 1.000.000 DM gewinnen - kostenlos tippen - http://millionenklick.web.de IhrName@web.de, 8MB Speicher, Verschluesselung - http://freemail.web.de From lonetwin@yahoo.com Mon Oct 15 11:27:25 2001 From: lonetwin@yahoo.com (lonetwin) Date: Mon, 15 Oct 2001 15:57:25 +0530 Subject: [Tutor] Another question about Variables in Threaded functions In-Reply-To: <4.2.0.58.20011012172733.00c564a0@pop3.norton.antivirus> References: <200110111903.f9BJ3Mx10101@calcifer.valdyas.org> <4.2.0.58.20011012172733.00c564a0@pop3.norton.antivirus> Message-ID: <01101515572500.04704@mercury.worli> Hi all, I asked a question a couple o' days back about class variables when one uses threads...an' I learned (thanx to Boudewijn and Kirby) about locking ...now I want to know this ...suppose I call a function from the run() method of my threaded class...and pass to it a local (local to run()) variable, a) how should I be doing this ?? (what should I keep in mind ??) b) what happens to these local variable (and to the local variables of the function being called) ??..are these too shared between threads ?? OK...Ok.... I know I'm not too good at framing questions....so like I did earlier ..here's some pseudo-code: ============================================== import threading import time class ThreadedFoo(threading.Thread): FooBox = range(100) def __init__(self, lock): threading.Thread.__init__(self) self.lock = lock def run(self): print "Started ", self.getName() while 1: self.lock.acquire() try: if len(self.FooBox) == 0: break Goody = self.FooBox.pop() # Is Goody shared ?? I think not # Am I wrong ?? self.doStuff(Goody) # what happens here ?? finally: self.lock.release() time.sleep(1) def doStuff(self, thingy): BoxOStuff = ['pink', 'yellow', 'green', 'blue', 'red' ] # Is ^^^^ this shared ?? ...again I don't think so..but I'm not sure for item in BoxOStuff: # What is happening here ?? print self.getName(), thingy, item if __name__ == '__main__': FooThreadBag = [] SharedLock = threading.Lock() for x in range(3): thread = ThreadedFoo(SharedLock) FooThreadBag.append(thread) for thread in FooThreadBag: thread.start() print "done" ============================================ So, that's it...Kirby's explanation leads me to believe that 'Goody' and 'BoxOStuff' are not shared....but I want someone to actually tell me that...anyways, thanx for your time. Peace Steve ---------------------------------------------- Every oak tree started out as a couple of nuts who stood their ground. Anonymous ---------------------------------------------- From boud@valdyas.org Mon Oct 15 11:56:39 2001 From: boud@valdyas.org (Boudewijn Rempt) Date: Mon, 15 Oct 2001 12:56:39 +0200 (CEST) Subject: [Tutor] Another question about Variables in Threaded functions In-Reply-To: <01101515572500.04704@mercury.worli> Message-ID: On Mon, 15 Oct 2001, lonetwin wrote: > So, that's it...Kirby's explanation leads me to believe that 'Goody' > and 'BoxOStuff' are not shared....but I want someone to actually tell me > that...anyways, thanx for your time. > Yes, that's right - because these variables are local to the function they will be created anew every time the function is called. Boudewijn Rempt | http://www.valdyas.org From toodles@yifan.net Mon Oct 15 12:36:33 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Mon, 15 Oct 2001 19:36:33 +0800 Subject: [Tutor] seed & random !? References: <20011014104552.25868.qmail@web9203.mail.yahoo.com> <20011014053814.A28032@sill.silmarill.org> <20011014104552.25868.qmail@web9203.mail.yahoo.com> <4.2.0.58.20011014173504.00c554e0@pop3.norton.antivirus> Message-ID: <001a01c1556d$a648ce30$0300a8c0@sun> > Indeed. Below is a function that takes a list of characters > and returns all unique permutations thereof: That's a funky function, Kirby! I'm wondering if there's a better way to extend this function, so that it returns permutations of specific numbers of elements, than what I have (by modifying your code). Andrew def perm_n(set,n,t=-1): """ Function by Kirby Urner. Thanks to Daniel Ajoy for sharing his Logo version with me. Modified by Andrew Wilkins to allow specific number of elements in each permutation. """ set=listify(set) if t==-1: if 0>n>len(set): return [] else: t=n if n==0 or len(set)==0: return [] elif n==1: return [listify(element) for element in set] elif len(set)==1: return set answ = [] for i in range(len(set)): base = [set[0]] rest = set[1:] if t>1: answ = answ + [base + listify(i) for i in perm_n(rest,n,t-1)] else: answ = answ + [base] set = [set[-1]]+set[:-1] return answ def listify(obj): "Just so I can use tuples...eg. perm_n(range(10))." if type(obj) is not type([]): try: l=list(obj) except: l=[obj] return l else: return obj > > > def perm(set): > """ > Return all permutations of a set. Thanks to > Daniel Ajoy for sharing his Logo version with me. > """ > > if len(set)==0: return [] > if len(set)==1: return set > > answ = [] > > for i in range(len(set)): > base = [set[0]] > rest = set[1:] > answ = answ + [base + list(i) for i in perm(rest)] > set = [set[-1]]+set[:-1] > > return answ > > >>> perm(['1','2','3']) > [['1', '2', '3'], ['1', '3', '2'], ['3', '1', '2'], > ['3', '2', '1'], ['2', '3', '1'], ['2', '1', '3']] > > >>> perm(['1','2','3','4']) > [['1', '2', '3', '4'], ['1', '2', '4', '3'], > ['1', '4', '2', '3'], ['1', '4', '3', '2'], > ['1', '3', '4', '2'], ['1', '3', '2', '4'], > ['4', '1', '2', '3'], ['4', '1', '3', '2'], > ['4', '3', '1', '2'], ['4', '3', '2', '1'], > ['4', '2', '3', '1'], ['4', '2', '1', '3'], > ['3', '4', '1', '2'], ['3', '4', '2', '1'], > ['3', '2', '4', '1'], ['3', '2', '1', '4'], > ['3', '1', '2', '4'], ['3', '1', '4', '2'], > ['2', '3', '4', '1'], ['2', '3', '1', '4'], > ['2', '1', '3', '4'], ['2', '1', '4', '3'], > ['2', '4', '1', '3'], ['2', '4', '3', '1']] > > I use it in my simplematrix module as part of what's needed > to get the determinant of a matrix. > > Nothing random about it though. > > Kirby > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From arcege@speakeasy.net Mon Oct 15 15:03:47 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Mon, 15 Oct 2001 10:03:47 -0400 Subject: [Tutor] Another question about Variables in Threaded functions In-Reply-To: <01101515572500.04704@mercury.worli>; from lonetwin@yahoo.com on Mon, Oct 15, 2001 at 03:57:25PM +0530 References: <200110111903.f9BJ3Mx10101@calcifer.valdyas.org> <4.2.0.58.20011012172733.00c564a0@pop3.norton.antivirus> <01101515572500.04704@mercury.worli> Message-ID: <20011015100347.E982@speakeasy.net> On Mon, Oct 15, 2001 at 03:57:25PM +0530, lonetwin wrote: > I asked a question a couple o' days back about class variables when one > uses threads...an' I learned (thanx to Boudewijn and Kirby) about locking > ...now I want to know this ...suppose I call a function from the run() method > of my threaded class...and pass to it a local (local to run()) variable, > a) how should I be doing this ?? (what should I keep in mind ??) > b) what happens to these local variable (and to the local variables of the > function being called) ??..are these too shared between threads ?? Local variables are not shared between threads. Each thread has a stack of running function contexts, and each of those functions have a new namespace for the local variables for that function. Here is an example. The theading._get_ident() function returns an integer that is _unique_ to the thread. The two threads, f and g, will increment their copies of eachs ident number, as a local variable inside the run() method. >>> import theading, time >>> class UnsharedThread(threading.Thread): ... def run(self): ... i = threading._get_ident() ... for n in range(20): ... print self, i ... i = i + 1 ... time.sleep(1) ... >>> f, g = UnsharedThread(), UnsharedThread() >>> f.start(), g.start() (None, None) >>> 3074 4099 3075 4100 3076 4101 3077 4102 3078 4103 3079 4104 3080 4105 3081 4106 3082 4107 3083 4108 3084 4109 3085 4110 3086 4111 3087 4112 3088 4113 3089 4114 3090 4115 3091 4116 3092 4117 3093 4118 This would be the same for any method/function called from the run() method. >>> > OK...Ok.... I know I'm not too good at framing questions....so like I did > earlier ..here's some pseudo-code: > ============================================== > import threading > import time > > class ThreadedFoo(threading.Thread): > FooBox = range(100) > def __init__(self, lock): > threading.Thread.__init__(self) > self.lock = lock > > def run(self): > print "Started ", self.getName() > while 1: > > self.lock.acquire() > try: > if len(self.FooBox) == 0: > break > Goody = self.FooBox.pop() # Is Goody shared ?? I think not > # Am I wrong ?? > self.doStuff(Goody) # what happens here ?? > finally: > self.lock.release() > time.sleep(1) > > def doStuff(self, thingy): > BoxOStuff = ['pink', 'yellow', 'green', 'blue', 'red' ] > # Is ^^^^ this shared ?? ...again I don't think so..but I'm not sure > for item in BoxOStuff: # What is happening here ?? > print self.getName(), thingy, item No, BoxOStuff is not shared, but if you made BoxOStuff a class member, then it would be. For example, the class member FooBox is shared. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From Blake.Garretson@dana.com Mon Oct 15 15:55:13 2001 From: Blake.Garretson@dana.com (Blake.Garretson@dana.com) Date: Mon, 15 Oct 2001 10:55:13 -0400 Subject: [Tutor] Removing characters Message-ID: Danny already posted a much better program, but here's my version that I wrote a while ago that does something similar. This overwrites the file, but you could easily change it to write to a different file. # strips off endline stuff import sys, string for filename in sys.argv[1:]: infile=open(filename,'r') text=file.read() text=string.replace(text,"\n","") text=string.replace(text,"\r","") infile.close() outfile=open(filename,'w') outfile.write(text) outfile.close() -Blake Garretson >Date: Sun, 14 Oct 2001 19:38:27 -0400 (EDT) >From: "Timothy M. Brauch" >Subject: [Tutor] Removing characters > >I know there must a simple way to open a file and remove all the end of >line characters and/or carriage returns. However, I can't seem to get it >to work right. Any help? > > - Tim From Blake.Garretson@dana.com Mon Oct 15 18:54:05 2001 From: Blake.Garretson@dana.com (Blake.Garretson@dana.com) Date: Mon, 15 Oct 2001 13:54:05 -0400 Subject: [Tutor] (no subject) Message-ID: Sharriff, If you don't want to make them from scratch, Tkinter has some built-in file browsers that work quite well. Try this: >>>import tkFileDialog >>>file=tkFileDialog.askopenfilename(filetypes=[("My Text Files", "*.txt"), ("All Files","*")]) The variable "file" holds the file name. The function should return None if cancel was hit. Also, if you look in the tkFileDialog.py source, it shows how to set a default file name, change the window's title, and other things. There's also a tkFileDialog.asksaveasfilename function. -Blake Garretson >Date: Mon, 15 Oct 2001 12:08:46 +0200 >From: "Sharriff Aina" >Subject: [Tutor] Tkinter File browswer > >Could someone show me how to code a file browser widget with Tkinter and Pmw? From dyoo@hkn.eecs.berkeley.edu Mon Oct 15 19:53:50 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 15 Oct 2001 11:53:50 -0700 (PDT) Subject: [Tutor] finding title tag In-Reply-To: Message-ID: On Mon, 15 Oct 2001, Samir Patel wrote: > i have written a program which takes in the url at command line > argument and finds the links present in that particular web page and > this continues to a depth of 3 or more..... > i store this links in a universal list ..now my problem is that i want > to find if there's any title tag present in this link e.g > > or this If we're using one of the parsers from the standard library, like HTMLParser or SGMLParser, this isn't too hard --- for each tag that the parser encounters, the parser will give us a list of attributes. > def findlinks(url): > try: > fp = urllib.urlopen(url) > except IOError: > return [] > results = [] > > p = HTMLParser(NullFormatter()) > p.feed(fp.read()) > > return p.anchorlist # return the list of lines which have a link htmllib.HTMLParser is a little more specialized as a parser than sgmllib.SGMLParser --- from the documentation, the HTMLParser only expects 'name' and 'type' attributes from the anchors tags. I think it might be too specialized for the task, as it doesn't pay attention to the titles of anchors. (At the same time, should the anchors have titles in the first place? Is this standard HTML?) It might be best to write our own parser to handle both the list of anchors and the list of titles. Here's one parser that should do the job: ### from sgmllib import SGMLParser class AnchorParser(SGMLParser): """This class pays attention to anchor tags. Once we feed() a document into an AnchorParser, we'd have the hrefs in the 'anchorlist' attribute, and the titles in the 'titlelist' attribute.""" def __init__(self): SGMLParser.__init__(self) self.anchorlist = [] self.titlelist = [] def start_a(self, attributes): """For each anchor tag, pay attention to the href and title attributes.""" href, title = '', '' for name, value in attributes: if name == 'href': href = value if name == 'title': title = value self.anchorlist.append(href) self.titlelist.append(title) def end_a(self): pass ### If we have something like AnchorParser, we can write a findtitles() function that looks very similar to your findlinks(): ### def findlinks(url): try: fp = urllib.urlopen(url) except IOError: return [] p = AnchorParser() p.feed(fp.read()) return p.titlelist ### If you're doing to do a lot of parsing, it might be a good idea to read more about sgmllib.SGMLParser: http://www.python.org/doc/lib/module-sgmllib.html Feel free to ask more questions. Good luck to you! From urnerk@qwest.net Mon Oct 15 22:32:22 2001 From: urnerk@qwest.net (Kirby Urner) Date: Mon, 15 Oct 2001 14:32:22 -0700 Subject: [Tutor] seed & random !? In-Reply-To: <001a01c1556d$a648ce30$0300a8c0@sun> References: <20011014104552.25868.qmail@web9203.mail.yahoo.com> <20011014053814.A28032@sill.silmarill.org> <20011014104552.25868.qmail@web9203.mail.yahoo.com> <4.2.0.58.20011014173504.00c554e0@pop3.norton.antivirus> Message-ID: <4.2.0.58.20011015135658.00c5db90@pop3.norton.antivirus> At 07:36 PM 10/15/2001 +0800, Andrew Wilkins wrote: > > Indeed. Below is a function that takes a list of characters > > and returns all unique permutations thereof: > >That's a funky function, Kirby! >I'm wondering if there's a better way to extend this function, >so that it returns permutations of specific numbers of elements, >than what I have (by modifying your code). > >Andrew In practice, permuting 10 or more items is impractical. So if you're willing to live with a 10 object limit, you could get away with mapping whatever 10 objects to single characters '0'..'9' using a dictionary, permuting those characters, and restoring the objects via dictionary lookup: def ultra_perm(objs): if len(objs)>10: raise ValueError,"To big to handle" index = 0 permdict = {} for o in objs: permdict[str(index)]=o index += 1 perms = perm(permdict.keys()) output = [tuple([permdict[entry] for entry in p]) \ for p in perms] return output (code for perm() in earlier post). Now you can go: >>> ultra_perm(range(3)) [(1, 0, 2), (1, 2, 0), (2, 1, 0), (2, 0, 1), (0, 2, 1), (0, 1, 2)] Or even: >>> ultra_perm(['a1',2,['a',1]]) [(2, 'a1', ['a', 1]), (2, ['a', 1], 'a1'), (['a', 1], 2, 'a1'), (['a', 1], 'a1', 2), ('a1', ['a', 1], 2), ('a1', 2, ['a', 1])] The original perm() function failed for multicharacter strings, e.g. perm(('x1','x2')) returned: >>> perm(['x1','x2']) [['x1', 'x', '2'], ['x2', 'x', '1']] Clearly not what's intended. A version of your listify() rectifies this problem: def listify(obj): """ Prevent breakdown of string objects, into lists of characters, with thanks to Andrew Wilkins """ if type(obj)==type(''): return [obj] else: return list(obj) def perm(set): """ Return all permutations of a set. Thanks to Daniel Ajoy for sharing his Logo version with me. """ if len(set)==0: return [] if len(set)==1: return set answ = [] for i in range(len(set)): base = [set[0]] rest = set[1:] answ = answ + [base + listify(i) for i in perm(rest)] set = [set[-1]]+set[:-1] return answ With this modification, we can go: >>> perm(['x1','x2']) [['x1', 'x2'], ['x2', 'x1']] With this modification in place, it's now possible, even if impractical, to go beyond the 10 object limit in ultra_perm. Kirby From dyoo@hkn.eecs.berkeley.edu Tue Oct 16 03:51:09 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 15 Oct 2001 19:51:09 -0700 (PDT) Subject: [Tutor] Intro to CS (boolean.py) In-Reply-To: <4.2.0.58.20011014211527.00c59570@pop3.norton.antivirus> Message-ID: On Sun, 14 Oct 2001, Kirby Urner wrote: > At 05:39 PM 10/14/2001 -0700, Danny Yoo wrote: > >Hi Kirby, > > > >I've written a small "propositional logic" parser class that you might > >find useful: > > > > http://hkn.eecs.berkeley.edu/~dyoo/python/propositions/ > > > >I wrote it as an experiment with the Spark parser-generator a month ago. I > >haven't been working on it for a while now, and you're welcome to use the > >parser if it's useful for you. > > > Impressive stuff Danny, as well as your plans for future > features :-D. > > I don't see 0.3 up yet, but this is a thread I'd like to > track. There could be some fun curriculum written around > here. Ok, I put the newest version on my site. The code is still a little messy; I think I need a day to clean things up and add test cases and documentation. If only I could clone() myself. *grin* Hope this helps! From nhytro-python@web.de Tue Oct 16 07:51:11 2001 From: nhytro-python@web.de (Sharriff Aina) Date: Tue, 16 Oct 2001 08:51:11 +0200 Subject: [Tutor] To Class or not to class Message-ID: <200110160651.f9G6pBu26134@mailgate5.cinetic.de> I=B4m writing a small GUI frontend for a dos app using Tkinter and Pmw, afte= r much progress, I ran into problems originated from nested widgets, for e= xample, my app instantiates a frame, this frame is the parent of a Noteboo= k widget, this notebook widget holds a few GROUP widgets, these widgets ho= ld in turn buttons, check boxes, entry fileds e.t.c, and it goes on and on= . My problem is that after a while, some functions which I wrote just stop= ped working. I know that it=B4s due to my "cut and pate" technique; I read a= tutorial that stated that it was good practise to encapsule all ones GUI = apps in a class, so I decided to build on a simple application that demons= trates this. Back to my question, I think if I had written the app step by step in a li= near fashion( using classes to build apps is newbie land for me) I would n= ot have run into these problems. Could some state the advantages of using = classes in building apps for me apart from the fact that one uses this met= hod to separate GUI code from Buisiness logic=3F also is there a simple gui= ldline to follow, example; class methods first the the code for the constr= uctor=3F =20 =5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F 1.000.000 DM gewinnen - kostenlos tippen - http://millionenklick.web.de IhrName@web.de, 8MB Speicher, Verschluesselung - http://freemail.web.de From nhytro-python@web.de Tue Oct 16 09:01:10 2001 From: nhytro-python@web.de (Sharriff Aina) Date: Tue, 16 Oct 2001 10:01:10 +0200 Subject: [Tutor] Class instantiation of a GUI app Message-ID: <200110160801.f9G81Au15663@mailgate5.cinetic.de> Given this snippet: class MainApp: ....def __init__(self, root=0): ........# create main application ........root = Tk() why does the root have to have a default 0? leaving the default value off creates an error. Thanks _______________________________________________________________________ 1.000.000 DM gewinnen - kostenlos tippen - http://millionenklick.web.de IhrName@web.de, 8MB Speicher, Verschluesselung - http://freemail.web.de From toodles@yifan.net Tue Oct 16 09:27:02 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Tue, 16 Oct 2001 16:27:02 +0800 Subject: [Tutor] Class instantiation of a GUI app References: <200110160801.f9G81Au15663@mailgate5.cinetic.de> Message-ID: <000501c1561c$560f97a0$0300a8c0@sun> Where does this snippet come from? Is this perfectly "cut 'n' pasted"? It would be more useful as something like: ... def __init__(self,root=0): if not root: root=Tk() ... So you can instantiate the class with a pre-existing root. But if you've "cut 'n' pasted" it, I guess that doesn't explain much... Andrew ----- Original Message ----- From: "Sharriff Aina" To: "Python-Tutor" Sent: Tuesday, October 16, 2001 4:01 PM Subject: [Tutor] Class instantiation of a GUI app > Given this snippet: > > class MainApp: > ....def __init__(self, root=0): > > ........# create main application > ........root = Tk() > > > why does the root have to have a default 0? leaving the default value off creates an error. > > > Thanks > _______________________________________________________________________ > 1.000.000 DM gewinnen - kostenlos tippen - http://millionenklick.web.de > IhrName@web.de, 8MB Speicher, Verschluesselung - http://freemail.web.de > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From nhytro-python@web.de Tue Oct 16 12:38:10 2001 From: nhytro-python@web.de (Sharriff Aina) Date: Tue, 16 Oct 2001 13:38:10 +0200 Subject: [Tutor] Pmw question Message-ID: <200110161138.f9GBcAu22176@mailgate5.cinetic.de> I have coded this small app as a test, can someone tell me why the "about menu does not show? ################## code import Pmw from tkFileDialog import askopenfilename from Tkinter import * # variables and constants filepath = "" # create main application root = Tk() # initialise Pmw for use Pmw.initialise(root) Pmw.aboutversion('0.5') Pmw.aboutcopyright('Copyright Sharriff Aina, 2001\nAll rights reserved') Pmw.aboutcontact('email: test@nowhere.de') # construct about dialogue about = Pmw.AboutDialog(root, applicationname = 'test_apllication') about.withdraw() # create root frame appframe = Frame(root, width = 400, height = 550) # create menu menubar = Menu(root, border=1) # create submenu "file" filemenu = Menu(menubar, tearoff = 0) filemenu.add_command(label = "Exit", command = root.quit) #add submenu "file" to mainmenu "menubar" menubar.add_cascade(label="File", menu=filemenu) #create submenu "Help" helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label = "menu1") helpmenu.add_command(label = "menu2") # add submenu "Help" to menubar menubar.add_cascade(label="Help", menu=helpmenu) def dialogue_about(): ....about.show() #create submenu "About" aboutmenu = Menu(menubar, tearoff=0) aboutmenu.add_command(label = "About") # add submenu "about" to menubar menubar.add_cascade(label="About", menu=aboutmenu, command = dialogue_about) appframe.pack() # set the title root.title("testapplication") #assign root a menubar root.config(menu=menubar) root.mainloop() _______________________________________________________________________ 1.000.000 DM gewinnen - kostenlos tippen - http://millionenklick.web.de IhrName@web.de, 8MB Speicher, Verschluesselung - http://freemail.web.de From dsh8290@rit.edu Tue Oct 16 16:45:25 2001 From: dsh8290@rit.edu (dman) Date: Tue, 16 Oct 2001 11:45:25 -0400 Subject: [Tutor] To Class or not to class In-Reply-To: <200110160651.f9G6pBu26134@mailgate5.cinetic.de>; from nhytro-python@web.de on Tue, Oct 16, 2001 at 08:51:11AM +0200 References: <200110160651.f9G6pBu26134@mailgate5.cinetic.de> Message-ID: <20011016114525.A27396@harmony.cs.rit.edu> On Tue, Oct 16, 2001 at 08:51:11AM +0200, Sharriff Aina wrote: | I=B4m writing a small GUI frontend for a dos app using Tkinter and Pmw, | after much progress, I ran into problems originated from nested | widgets, for example, my app instantiates a frame, this frame is the | parent of a Notebook widget, this notebook widget holds a few GROUP | widgets, these widgets hold in turn buttons, check boxes, entry fileds | e.t.c, and it goes on and on. My problem is that after a while, some | functions which I wrote just stopped working. I know that it=B4s due to | my "cut and pate" technique; I read a tutorial that stated that it was | good practise to encapsule all ones GUI apps in a class, so I decided | to build on a simple application that demonstrates this. |=20 | Back to my question, I think if I had written the app step by step in | a linear fashion( using classes to build apps is newbie land for me) I | would not have run into these problems. Could some state the | advantages of using classes in building apps for me apart from the | fact that one uses this method to separate GUI code from Buisiness | logic? also is there a simple guildline to follow, example; class | methods first the the code for the constructor? If you organize your application using classes what you can do is encapsulate the complex widgets as custom classes. These classes provide access to the application-specific data (such as the app-specific data corresponding to the currently selected item in a list) and allow convenient manipulation of your application's data. For example, you mentioned that you have a GROUP in your application. You can write a class that handles this GROUP. It could subclass the Panel class (or some sort of container widget that Tk/Pmw have). Then you can add an instance of your group class to the frame or whatever and it will be drawn correctly. The GROUP class will handle adding the specific widgets (radio buttons, whatever) into itself so the parent really doesn't care. You hold onto a reference to the GROUP and when the user clicks a button you can then query the GROUP object to find out what is currently selected. This query is done via specialized methods that you put in the GROUP class that are specific to your applictation. HTH, -D From bob_lunney@yahoo.com Tue Oct 16 17:29:43 2001 From: bob_lunney@yahoo.com (Bob Lunney) Date: Tue, 16 Oct 2001 09:29:43 -0700 (PDT) Subject: [Tutor] Reuse output line on stdout Message-ID: <20011016162943.44115.qmail@web9707.mail.yahoo.com> Total Python newbie here. I have a loop that reads and processes lines in a file. I want some feedback so I have my script print the line number under process to stdout. Since these files can contain several hundred thousand lines how do I get Python to reuse the same line on stdout, i.e. I don't want a newline/linefeed at the end of the output line, I just want to increment the line number on the input as it increments in my for loop. Any way to do this without resorting to Tkinter? Bob Lunney __________________________________________________ Do You Yahoo!? Make a great connection at Yahoo! Personals. http://personals.yahoo.com From jeff@ccvcorp.com Tue Oct 16 17:45:22 2001 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue, 16 Oct 2001 09:45:22 -0700 Subject: [Tutor] Class instantiation of a GUI app References: Message-ID: <3BCC6421.229A1B94@ccvcorp.com> > From: "Sharriff Aina" > > class MainApp: > ....def __init__(self, root=0): > > ........# create main application > ........root = Tk() > This snippet has another problem, in that once the __init__() function ends, root goes out of scope and is garbage-collected--this is probably not what you want. (It may work if you call root.mainloop() at the end of this function, and the entire app is *intended* to shut down once __init__() finishes, though this seems like an odd design to me...) You probably want to save a reference to root as a member variable. Try using self.root = Tk() instead, and make all your other references to root be for self.root, as well. Jeff Shannon Technician/Programmer Credit International From gbcs1978@hotmail.com Tue Oct 16 18:52:44 2001 From: gbcs1978@hotmail.com (Glauco Silva) Date: Tue, 16 Oct 2001 14:52:44 -0300 Subject: [Tutor] Help Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0005_01C15652.369AB4A0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi ,=20 I would like to know if the lib wxPython isn't compatible with = Tkinter because i'm whith problem : - I start to make a program using Tkinter and i want to use a = function that only have in the wxPython and i'm not getting .=20 If somebody know a solution , please help me . This is a slice of my code : self.midframe41 =3D Frame(self.midframe4) self.midframe41.pack(side =3D LEFT) =20 =20 tID =3D wxNewId() =20 self.list =3D wxListCtrl(self.midframe41 , tID , = style=3DwxLC_REPORT|wxSUNKEN_BORDER) # ^ # | # the problem is here . I can't use = the parent like a Frame of Tkinter.=20 self.list.InsertColumn(0, "Artist") self.list.InsertColumn(1, "Title", wxLIST_FORMAT_RIGHT) self.list.InsertColumn(2, "Genre") self.midframe41.Show(true) Thank you Glauco ------=_NextPart_000_0005_01C15652.369AB4A0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi ,
 
    I would like to know = if the lib=20 wxPython isn't compatible with Tkinter because i'm whith problem = :
    - I start to make a = program=20 using Tkinter and i want to use a function that only have in the = wxPython and=20 i'm not getting .
   If somebody know a = solution , please=20 help me .
    This is a slice of = my code=20 :
 
      = self.midframe41 =3D=20 Frame(self.midframe4)
     =20 self.midframe41.pack(side =3D=20 LEFT)      
    &nbs= p;      
     &= nbsp;=20 tID =3D wxNewId()       =20
       self.list =3D = wxListCtrl(self.midframe41=20 , tID ,  style=3DwxLC_REPORT|wxSUNKEN_BORDER)
       =20             =    =20           #  =    =20     ^
          &nbs= p;            = ;          = #          =20 |
       =20             =    =20          #   the problem is = here=20 .  I can't use the parent like a Frame of Tkinter. =

      =20 self.list.InsertColumn(0, = "Artist")
      =20 self.list.InsertColumn(1, "Title",=20 wxLIST_FORMAT_RIGHT)
      =20 self.list.InsertColumn(2, = "Genre")
      =20 self.midframe41.Show(true)
 
Thank you
Glauco
 
 
------=_NextPart_000_0005_01C15652.369AB4A0-- From scarblac@pino.selwerd.nl Tue Oct 16 17:56:01 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Tue, 16 Oct 2001 18:56:01 +0200 Subject: [Tutor] Reuse output line on stdout In-Reply-To: <20011016162943.44115.qmail@web9707.mail.yahoo.com>; from bob_lunney@yahoo.com on Tue, Oct 16, 2001 at 09:29:43AM -0700 References: <20011016162943.44115.qmail@web9707.mail.yahoo.com> Message-ID: <20011016185601.A3091@pino.selwerd.nl> On 0, Bob Lunney wrote: > Total Python newbie here. I have a loop that reads > and processes lines in a file. I want some feedback > so I have my script print the line number under > process to stdout. Since these files can contain > several hundred thousand lines how do I get Python to > reuse the same line on stdout, i.e. I don't want a > newline/linefeed at the end of the output line, I just > want to increment the line number on the input as it > increments in my for loop. Any way to do this without > resorting to Tkinter? Depends on your platform. On Linux/Unix terminals at least, you can print "\r" to go back to the beginning of the line. Don't know if that works in DOS boxes on Windows. -- Remco Gerlich From shalehperry@home.com Tue Oct 16 17:56:10 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Tue, 16 Oct 2001 09:56:10 -0700 (PDT) Subject: [Tutor] wouldn't it be nice ..... Message-ID: if this list would block any mail whose subject matched r'^\s*help\s*$'? Please boys and girls tells us what you need. 'I dont understand classes', 'why is python dying', 'help me with my homework because I am lazy and just go to school to get a degree to go out and make money'. Whatever, just give us something to go on. From dyoo@hkn.eecs.berkeley.edu Tue Oct 16 19:07:46 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 16 Oct 2001 11:07:46 -0700 (PDT) Subject: [Tutor] finding title tag (fwd) Message-ID: Dear Samir, I'm slightly busy at the moment, but I'll be able to answer your question tonight. I'm forwarding this to the other tutors on the mailing list, so that someone has a chance to answer you. Best of wishes! ---------- Forwarded message ---------- Date: Tue, 16 Oct 2001 17:22:14 +1000 (EST) From: Samir Patel To: Danny Yoo Subject: Re: [Tutor] finding title tag hi, thanx a lot for the help... i am confused with the use of class ....as i want to find links at the depth of 3 or more how can i recursively call this method..... also in following soln of yours it will separate links and title for that links ..so i will not be able to keep track of which title belongs to which link....and also if there's no title then i have to get the text of the link thank you smair On Mon, 15 Oct 2001, Danny Yoo wrote: > On Mon, 15 Oct 2001, Samir Patel wrote: > > > i have written a program which takes in the url at command line > > argument and finds the links present in that particular web page and > > this continues to a depth of 3 or more..... > > > i store this links in a universal list ..now my problem is that i want > > to find if there's any title tag present in this link e.g > > > > or this > > If we're using one of the parsers from the standard library, like > HTMLParser or SGMLParser, this isn't too hard --- for each tag that the > parser encounters, the parser will give us a list of attributes. > > > > > def findlinks(url): > > try: > > fp = urllib.urlopen(url) > > except IOError: > > return [] > > results = [] > > > > p = HTMLParser(NullFormatter()) > > p.feed(fp.read()) > > > > return p.anchorlist # return the list of lines which have a link > > > htmllib.HTMLParser is a little more specialized as a parser than > sgmllib.SGMLParser --- from the documentation, the HTMLParser only expects > 'name' and 'type' attributes from the anchors tags. I think it might be > too specialized for the task, as it doesn't pay attention to the titles of > anchors. > > (At the same time, should the anchors have titles in the first place? Is > this standard HTML?) > > > It might be best to write our own parser to handle both the list of > anchors and the list of titles. Here's one parser that should do the job: > > ### > from sgmllib import SGMLParser > > class AnchorParser(SGMLParser): > """This class pays attention to anchor tags. Once we feed() a > document into an AnchorParser, we'd have the hrefs in the > 'anchorlist' attribute, and the titles in the 'titlelist' > attribute.""" > def __init__(self): > SGMLParser.__init__(self) > self.anchorlist = [] > self.titlelist = [] > > def start_a(self, attributes): > """For each anchor tag, pay attention to the href and title > attributes.""" > href, title = '', '' > for name, value in attributes: > if name == 'href': href = value > if name == 'title': title = value > self.anchorlist.append(href) > self.titlelist.append(title) > > def end_a(self): > pass > ### > > > > If we have something like AnchorParser, we can write a > findtitles() function that looks very similar to your findlinks(): > > > ### > def findlinks(url): > try: > fp = urllib.urlopen(url) > except IOError: > return [] > p = AnchorParser() > p.feed(fp.read()) > return p.titlelist > ### > > > If you're doing to do a lot of parsing, it might be a good idea to read > more about sgmllib.SGMLParser: > > http://www.python.org/doc/lib/module-sgmllib.html > > Feel free to ask more questions. Good luck to you! > > From dsh8290@rit.edu Tue Oct 16 21:01:47 2001 From: dsh8290@rit.edu (dman) Date: Tue, 16 Oct 2001 16:01:47 -0400 Subject: [Tutor] help ;-) In-Reply-To: ; from shalehperry@home.com on Tue, Oct 16, 2001 at 09:56:10AM -0700 References: Message-ID: <20011016160147.A28016@harmony.cs.rit.edu> On Tue, Oct 16, 2001 at 09:56:10AM -0700, Sean 'Shaleh' Perry wrote: | if this list would block any mail whose subject matched r'^\s*help\s*$'? | | Please boys and girls tells us what you need. 'I dont understand | classes', 'why is python dying', 'help me with my homework because I | am lazy and just go to school to get a degree to go out and make | money'. Whatever, just give us something to go on. Yeah, I usually ignore messages that just say "help" because I don't have time to read everything. It the subject doesn't appear interesting and/or something I know about, I tend to ignore it. -D From rob@jam.rr.com Tue Oct 16 23:02:39 2001 From: rob@jam.rr.com (Rob Andrews) Date: Tue, 16 Oct 2001 17:02:39 -0500 Subject: [Tutor] help (for Useless Python) Message-ID: <3BCCAE7F.1020504@jam.rr.com> I'm working on the latest update to Useless Python, but I have to admit I've really dropped the ball. Scripts people sent me several weeks ago have yet to be posted, which is what I'm currently trying to resolve. This is due in part, but only in part, to freakish technical difficulties. When a fair bit of calamity overwhelmed me a few months ago, I lost weeks of programming work I'd done. I was also stiffed by customers and ran into a host of other hassles. A lot of other nonsense bit me simultaneously, and my business folded. And now I feel that if I don't relieve myself temporarily of some of my responsibilities (for a few good months at least) to free up time for rest and meditation, I will continue to leave Useless Python stagnating. If Useless was my project alone, I'd consider just letting it ride for a while. But I've always considered it a gift from Python Tutor to the newbies of the world, and I've been allowed the privilege of hosting and maintaining the site. My offer of unlimited hosting is still firmly in place. But I believe both the site and I will know better health if I focus more on dharma and less on code for a few months while the site is lovingly maintained by someone more focused on the task. In the meantime, feel free to continue to send scripts my way. But I confess that it may take longer than I feel is appropriate for me to get them up to the site. humbly, Rob Andrews http://www.lowerstandard.com/python/ From tonycervone@netzero.net Tue Oct 16 23:33:22 2001 From: tonycervone@netzero.net (tonycervone) Date: Tue, 16 Oct 2001 18:33:22 -0400 Subject: [Tutor] printing a word in a line Message-ID: <000e01c15692$9187e1e0$568cf4d1@w9y5d5> This is a multi-part message in MIME format. ------=_NextPart_000_000B_01C15671.09408100 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable How do I read a text file and then print the word that is located in a = specific location in the first line of that text ? thank you in = advance. ------=_NextPart_000_000B_01C15671.09408100 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
How do I read a text file and then = print the word=20 that is located in a specific location in the first line of = that=20  text ? thank you in advance.
------=_NextPart_000_000B_01C15671.09408100-- ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From lkvam@venix.com Wed Oct 17 00:09:43 2001 From: lkvam@venix.com (Lloyd Kvam) Date: Tue, 16 Oct 2001 19:09:43 -0400 Subject: [Tutor] printing a word in a line References: <000e01c15692$9187e1e0$568cf4d1@w9y5d5> Message-ID: <3BCCBE37.1A135098@venix.com> Maybe this snippet helps: line = "Now is the time for all good men to come to the aid of their country" x = line.split(' ')[4] print x 'for' How do you know the specific location? Is it a word count? > tonycervone wrote: > > How do I read a text file and then print the word that is located in a specific location in the first line of that text ? thank you in advance. -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From dyoo@hkn.eecs.berkeley.edu Wed Oct 17 02:52:20 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 16 Oct 2001 18:52:20 -0700 (PDT) Subject: [Tutor] finding title tag (fwd) In-Reply-To: Message-ID: On Tue, 16 Oct 2001, Danny Yoo wrote: > I'm slightly busy at the moment, but I'll be able to answer your question > tonight. I'm forwarding this to the other tutors on the mailing list, so > that someone has a chance to answer you. Best of wishes! Ok, I'm back. > thanx a lot for the help... > i am confused with the use of class ....as i want to find links at the > depth of 3 or more how can i recursively call this method..... How familiar are you with recursion? If you tell us more about your background, that will help allow us to better present things for you. Because recursion is an advanced topic, I don't know exactly how to effectively talk about this. It might help to think of findlinks() as a function that takes in a single url, and spits back a list of new urls. If trying to solve this problem recursively is difficult, let's go for the easy route: let's try to solve the problem without recursion. *grin* For example, we already know how to get the links at "depth 0" if we have an initial url we want to look at: ### links_at_depth_0 = findLinks('http://python.org') ### To get links at "depth 1", we can simply call findlinks() on each link that's at "depth 0", and collect all these links together: ### links_at_depth_1 = [] for link in links_at_depth_0: links_at_depth_1 = links_at_depth_1 + findLinks(link) ### To get to links at "depth 2", we can simply call findlinks() on each link that's at "depth 1", and collect all these links together: ### links_at_depth_2 = [] for link in links_at_depth_1: links_at_depth_2 = links_at_depth_2 + findLinks(link) ### Let's stop here. *grin* A recursive solution can capture this sort of link-grabbing as deeply as we want. But if you just want it for depth 3, you already have enough tools to do this. It will be a little wordy, true, but it will also be easy to understand. We can talk more about this if you want. Please feel free to ask more questions about this. > also in following soln of yours it will separate links and title for that > links ..so i will not be able to keep track of which title belongs to > which link The links and titles are intentionally paired up in a way so that if we're looking at a link a position 'n' in the anchorlist, its corresponding title will also be at position 'n' in the titlelist. Play around with it a little more. > ....and also if there's no title then i have to get the text of the > link Not too difficult; that will require a small change to the AnchorParser. How much of the AnchorParser class makes sense to you now? From mjyuen@hotmail.com Wed Oct 17 04:01:48 2001 From: mjyuen@hotmail.com (Mike Yuen) Date: Tue, 16 Oct 2001 21:01:48 -0600 Subject: [Tutor] Command Line Arguements in Python Message-ID: I'm having some trouble reading input and writing output files from the command line as follows: python myfile.py < inputfile.txt > outputfile.txt The problem is, I don't know how to get access to the inputfile.txt and outputfile.txt inside my code. Normally, i'm used to using the "open" command but I don't want to hard code it in anymore. FYI, i'm using Python on a UNIX O/S. Thanks, M _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp From dyoo@hkn.eecs.berkeley.edu Wed Oct 17 04:27:13 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 16 Oct 2001 20:27:13 -0700 (PDT) Subject: [Tutor] help ;-) In-Reply-To: <20011016160147.A28016@harmony.cs.rit.edu> Message-ID: On Tue, 16 Oct 2001, dman wrote: > On Tue, Oct 16, 2001 at 09:56:10AM -0700, Sean 'Shaleh' Perry wrote: > | if this list would block any mail whose subject matched r'^\s*help\s*$'? > | > | Please boys and girls tells us what you need. 'I dont understand > | classes', 'why is python dying', 'help me with my homework because I > | am lazy and just go to school to get a degree to go out and make > | money'. Whatever, just give us something to go on. > > Yeah, I usually ignore messages that just say "help" because I don't > have time to read everything. It the subject doesn't appear > interesting and/or something I know about, I tend to ignore it. [Warning: My post is a personal rant, and has little to do with programming in Python.] Yikes. This is starting to sound like something out of ESR's "How to ask Questions the Smart Way" FAQ: http://www.tuxedo.org/~esr/faqs/smart-questions.html It is sometimes a little demoralizing if we get questions that seem to beg for an answer without showing any effort at trying things out. But it is not unexpected: In the culture of education and knowledge, I feel there's an unhealthy tendency to emphasize "The Answer" at the expense of ignoring what motions or Process that people make toward a goal. Math drills do this. Multiple choice questions do this. The SAT does this. And game shows do this all the time. People in Jeopardy are considered geniuses if they can spit out "questions" at the chime of a buzzer, but that's still, in essence, just another Answer that's disconnected from any real understanding. Perhaps those contestants really do know the ideas behind the facts, or perhaps they're just parroting what they remembered from flash cards. How can one tell? Given a large enough database of facts, perhaps a Python dictionary could outperform Alex Trebek. It's my opinion that the educational culture in the United States does real damage to people by not encouraging people encogh to practicing the Process of discovering things. I feel that, instead, schools encourage the impulse to depend on others for an answer, without asking how or why that answer makes sense with what we already know. It's the path of least friction: it's just easier to lure the "teacher" to give an answer, rather than to discover it for oneself. This feeling seems echoed by John Holt's book, "How Children Fail", but perhaps I'm misinterpreting his words. How does this relate back to programming? I believe computer programming can help make Process important again. What makes programming so much different from other "intellectual" things that people can try out is that Process really does matter. One can't get good at programming without building models of what's going on, or without knowing how to ask good questions. When I learned programming, few teachers really knew how to program --- I couldn't depend on my teachers for an Answer, although I could ask them for suggestions on resources that could help me. Nor could I depend solely on reading books, because it was unlikely I could copy an exact answer in the back. But I could combine what I read about books, try interactive experiments with the computer, and try to build some sort of model that would solve what I was looking for. Programming made creativity and invention important again. And even if I couldn't figure out how exactly to solve a problem, I learned how to make things less confusing for myself. I have to admit, though, that I was a little lonely, not to be able to talk to other people about this crazy stuff about circular linked lists or binary arithmetic. I'd better tie this rant somehow with what was discussed earlier... > | Please boys and girls tells us what you need. 'I dont understand > | classes', 'why is python dying', 'help me with my homework because I > | am lazy and just go to school to get a degree to go out and make > | money'. Whatever, just give us something to go on. I agree that it would be nice if people put more effort in, but I think that this was a little rough. Quite a few people who are on Tutor are new at this "programming" sort of thing. Programming is different, alien, and unfamiliar enough that I think some liberties should be given to people who have just started something new. It takes time to break out bad habits, but the fact that people are actually talking to us, complete strangers, about things that aren't part of a standard school curriculum (yet), is a step in the right direction. Let's try to make sure people know that they are welcome here, and that we will do what we can to make it less intimidating. From dyoo@hkn.eecs.berkeley.edu Wed Oct 17 04:38:44 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 16 Oct 2001 20:38:44 -0700 (PDT) Subject: [Tutor] Command Line Arguements in Python In-Reply-To: Message-ID: On Tue, 16 Oct 2001, Mike Yuen wrote: > I'm having some trouble reading input and writing output files from the > command line as follows: > > python myfile.py < inputfile.txt > outputfile.txt > > The problem is, I don't know how to get access to the inputfile.txt > and outputfile.txt inside my code. Normally, i'm used to using the > "open" command but I don't want to hard code it in anymore. FYI, i'm > using Python on a UNIX O/S. Ah, you'll like this one. Take a look at 'sys.stdin' and 'sys.stdout': http://www.python.org/doc/current/lib/module-sys.html What you know already about file handles can apply directly to reading and writing to "standard input" and "standard output". The only difference is that these 'files' are already open(). Hope this helps! From shalehperry@home.com Wed Oct 17 06:24:01 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Tue, 16 Oct 2001 22:24:01 -0700 (PDT) Subject: [Tutor] help ;-) In-Reply-To: Message-ID: > > Let's try to make sure people know that they are welcome here, and that we > will do what we can to make it less intimidating. > My apology if anyone saw this as intimidating. I really was aiming this at the people who answer questions on this list, hopefully one of them has control over the actual list. Several of my emails have been held beause the length was not sufficient or for other reasons. Some magic person has ok'ed them. Would it be that much harder to deny messages with a subject of only 'help'? The mail from the bot could tell them to please add a better subject and resend. Even point them to ESR's great essay. ----- We have buried the putrid corpse of Liberty. -- Benito Mussolini From r.b.rigilink@chello.nl Wed Oct 17 07:00:37 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Wed, 17 Oct 2001 08:00:37 +0200 Subject: [Tutor] Command Line Arguements in Python References: Message-ID: <3BCD1E85.79A0CE7C@chello.nl> Mike Yuen wrote: > > I'm having some trouble reading input and writing output files from the > command line as follows: > > python myfile.py < inputfile.txt > outputfile.txt > > The problem is, I don't know how to get access to the inputfile.txt and > outputfile.txt inside my code. Normally, i'm used to using the "open" > command but I don't want to hard code it in anymore. FYI, i'm using Python > on a UNIX O/S. > > Thanks, > M > Hi Mike, Danny already told you about sys.stdin and sys.stdout You can also simply use (raw_)input() and print, which read from stdin and write to stdout respectively. Remember, inputfile.txt and outputfile.txt are not command line arguments. '>' and '<' are redirection operators which tell the OS to connect inputfile.txt (rather than the keybord) to the standard input stream and to connect outputfile.txt (rather than the terminal) to the output stream of a process. Hope this helps, Roeland -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From dyoo@hkn.eecs.berkeley.edu Wed Oct 17 09:08:29 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 17 Oct 2001 01:08:29 -0700 (PDT) Subject: [Tutor] help ;-) [How to Ask Good Questions] In-Reply-To: Message-ID: [Warning: no programming content again. This is more of a meta-question thing. We'll probably stop this thread soon.] On Tue, 16 Oct 2001, Sean 'Shaleh' Perry wrote: > > Let's try to make sure people know that they are welcome here, and > > that we will do what we can to make it less intimidating. > > My apology if anyone saw this as intimidating. I really was aiming > this at the people who answer questions on this list, hopefully one of > them has control over the actual list. Several of my emails have been > held beause the length was not sufficient or for other reasons. Some > magic person has ok'ed them. That magic person would either be Deirdre, Wesley, or me. *grin* I haven't hear from Deirdre or Wesley for a while, so it looks like I'm holding down the fort. I must apologize as well for being preachy in the last message. About getting your messages held: Mailman has some rules about filtering messages that are sometimes a little oversensitive. At the same time, they do appear to work most of the time: Spam flies at Tutor every day, but the manager intercepts before it hits the rest of the list. I try to laugh it off, but it's a little depressing to see how much automation goes into attacking a community of volunteers. > Would it be that much harder to deny messages with a subject of only > 'help'? The mail from the bot could tell them to please add a better > subject and resend. Even point them to ESR's great essay. Actually, the first time that anyone posts on Tutor, he or she will get an autoresponse from the mailing list manager with the following: """ Your message for tutor@python.org, the Python programming tutor list, has been received and is being delivered. This automated response is sent to those of you new to the Tutor list, to point out a few resources that can help with answering your own questions, or improve the chances of getting a useful answer from the other subscribers. ... [message cut] """ I'd be happy to add a link here to ESR's essay, but I should wait for a consensus from the other tutor-admins before making the change to the welcome text. ESR's "How to Ask Questions The Smart Way" essay is a funny and informative guide for newcomers to read before posting to a newsgroup or mailing list. http://www.tuxedo.org/~esr/faqs/smart-questions.html I do agree with many of his points. The biggest qualm I have about it, though, is that its language is really blunt. For example, calling people "losers" for not knowing about the customs and habits of a community is not the way I'd prefer to welcome people. *grin* However, I know he's using his language flamboyantly as a sort of "ha ha only serious" thing --- his writing wouldn't be so compelling if it wasn't so colorful. Also, I'm a bit hypersensitive about language and the connotations of words, so perhaps I'm worrying about nothing. About rejecting headers with the word "help" in them... er, I don't know about that one. What do other people think about this? As a disclaimer: I must admit bias about frowning about filtering "help" messages: I am trying to avoid unnecessary work as an admin. *grin* But seriously, every message that gets filtered hits me and the other admins for manual verification. I also don't feel too comfortable about this because the same configuration option is used to filter spammers... In the terms of Lawrence Lessig's book "Code", I'd personally prefer that making good message headers (and making good questions) be something encouraged by community norms and not enforced by code. Just my thoughts on that. Talk to you later! From scarblac@pino.selwerd.nl Wed Oct 17 09:41:30 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 17 Oct 2001 10:41:30 +0200 Subject: [Tutor] help ;-) [How to Ask Good Questions] In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Wed, Oct 17, 2001 at 01:08:29AM -0700 References: Message-ID: <20011017104130.A4037@pino.selwerd.nl> On 0, Danny Yoo wrote: > About rejecting headers with the word "help" in them... er, I don't know > about that one. What do other people think about this? I don't mind them (but heh, I'm not very active here at the moment). I'd rather hit enter on two "help" messages per day than scare one person away who'd gotten his first programming question refused because his subject line was not informative enough. > In the terms of Lawrence Lessig's book "Code", I'd personally prefer that > making good message headers (and making good questions) be something > encouraged by community norms and not enforced by code. Just my thoughts > on that. Well newbies here aren't really part of the programming community yet, are they? They'll learn about that sort of thing in time. And I don't think we should start filtering messages until society in general cleans up its act :-). -- Remco Gerlich From scarblac@pino.selwerd.nl Wed Oct 17 09:44:37 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 17 Oct 2001 10:44:37 +0200 Subject: [Tutor] Help In-Reply-To: ; from gbcs1978@hotmail.com on Tue, Oct 16, 2001 at 02:52:44PM -0300 References: Message-ID: <20011017104437.B4037@pino.selwerd.nl> On 0, Glauco Silva wrote: > I would like to know if the lib wxPython isn't compatible with Tkinter because i'm whith problem : > - I start to make a program using Tkinter and i want to use a function that only have in the wxPython and i'm not getting . > If somebody know a solution , please help me . Unfortunately, you can't mix two GUI frameworks. Internally, they are very different, and they weren't designed to be mixed with other systems. > This is a slice of my code : > > self.midframe41 = Frame(self.midframe4) > self.midframe41.pack(side = LEFT) > > tID = wxNewId() > self.list = wxListCtrl(self.midframe41 , tID , style=wxLC_REPORT|wxSUNKEN_BORDER) > # ^ > # | > # the problem is here . I can't use the parent like a Frame of Tkinter. Yes. Either you make your GUI using Tkinter, or you use wxPython, but you can't use both :-(. I think it's possible to get list controls in Tk, but I don't know how... -- Remco Gerlich From alan.gauld@bt.com Wed Oct 17 11:35:25 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 17 Oct 2001 11:35:25 +0100 Subject: [Tutor] Command Line Arguements in Python Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFFB@mbtlipnt02.btlabs.bt.co.uk> > I'm having some trouble reading input and writing output > files from the command line as follows: > > python myfile.py < inputfile.txt > outputfile.txt When you use indirection the files appear in stdin/stdout - thats what redirection does. So in your case you read input.txt with raw_input() You write to output.txt with print. You don't need to open the files the OS does that automatically. If you would rather have the files as parameters to your program then you access them with sys.argv as described in my online tutor at: http://www.freenetpages.co.uk/hp/alan.gauld/ Under 'talking to the user'. To do that you'd call yourt script like: python myfile.py input.txt output.txt ie no indirection. Also in this case you need to use open() and close(). HTH, Alan G. From alan.gauld@bt.com Wed Oct 17 11:38:09 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 17 Oct 2001 11:38:09 +0100 Subject: [Tutor] printing a word in a line Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFFC@mbtlipnt02.btlabs.bt.co.uk> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C156F7.D077AF60 Content-Type: text/plain; charset="iso-8859-1" How do I read a text file and then print the word that is located in a specific location in the first line of that text ? You probably shouldn't! If you only want to print that word then just read the first line: inp = popen('filename here') line = inp.readline() print line.split()[position] inp.close() Reading the whole file would be wasteful. Alan G ------_=_NextPart_001_01C156F7.D077AF60 Content-Type: text/html; charset="iso-8859-1"
How do I read a text file and then print the word that is located in a specific location in the first line of that  text ?  
You probably shouldn't!
If you only want to print that word then just read the first line:
 
inp = popen('filename here')
line = inp.readline()
print line.split()[position]
inp.close()
 
Reading the whole file would be wasteful.
 
Alan G
 
------_=_NextPart_001_01C156F7.D077AF60-- From lonetwin@yahoo.com Wed Oct 17 11:53:38 2001 From: lonetwin@yahoo.com (lonetwin) Date: Wed, 17 Oct 2001 16:23:38 +0530 Subject: [Tutor] Command Line Arguements in Python In-Reply-To: <3BCD1E85.79A0CE7C@chello.nl> References: <3BCD1E85.79A0CE7C@chello.nl> Message-ID: <01101716233802.03836@mercury.worli> Mike wrote: > > Normally, i'm used to using the "open" > > command but I don't want to hard code it in anymore. <-----------SNIP-------------> Hi Mike, Since your 'Subject' says Commandline Arguments and you also said that you 'don't ant to hard code it in anymore.' ....do you want to do something like: $ python myfile.py [input file name] [output file name] If this is what you want, then like you said 'to get access to the inputfile and outputfile' ....just import the sys module (insert the line import sys at the start of your proggy)...and the command line arguments would be available to you as a list sys.argv[] sys.argv[0] would be myfile.py sys.argv[1] would be the [input file name] sys.argv[2] would be the [output file name] Hope that's what you were looking for. Peace Steve -- ---------------------------------------------- Every oak tree started out as a couple of nuts who stood their ground. Anonymous ---------------------------------------------- From alan.gauld@bt.com Wed Oct 17 12:04:19 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 17 Oct 2001 12:04:19 +0100 Subject: [Tutor] Help Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFFD@mbtlipnt02.btlabs.bt.co.uk> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C156FB.78286DA0 Content-Type: text/plain; charset="iso-8859-1" I would like to know if the lib wxPython isn't compatible with Tkinter because In general mixing GUI libraries is a really bad idea and won't work. There are a few cases when it can be done - using the win32 message dialogs within a Tkinter prog works OK - but then Tkinter has its own so why not use them?! Mixing wxPython amnd Tk will be unlikely to work since they both assume that they have control of the main event loop. Your choices would therefore appear to be: - Use wxPython instead of Tkinter coz it has the widget(s) you need - Code equivalent widgets in Tkinter(and make them available on Parnassus or Useless?) - Find another way of working that uses standard widgets. Alan G. ------_=_NextPart_001_01C156FB.78286DA0 Content-Type: text/html; charset="iso-8859-1"
    I would like to know if the lib wxPython isn't compatible with Tkinter because  
In general mixing GUI libraries is a really bad idea
and won't work. There are a few cases when it can be
done - using the win32 message dialogs within a Tkinter
prog works OK - but then Tkinter has its own so why
not use them?!
 
Mixing wxPython amnd Tk will be unlikely to work since
they both assume that they have control of the main
event loop. Your choices would therefore appear to be:
 
- Use wxPython instead of Tkinter coz it has the
    widget(s) you need
- Code equivalent widgets in Tkinter(and make them
    available on Parnassus or Useless?)
- Find another way of working that uses standard widgets.
 
Alan G.
 
------_=_NextPart_001_01C156FB.78286DA0-- From lonetwin@yahoo.com Wed Oct 17 11:52:01 2001 From: lonetwin@yahoo.com (lonetwin) Date: Wed, 17 Oct 2001 16:22:01 +0530 Subject: [Tutor] Very OT [Re:help ;-) [How to Ask Good Questions]] In-Reply-To: <20011017104130.A4037@pino.selwerd.nl> References: <20011017104130.A4037@pino.selwerd.nl> Message-ID: <01101716220101.03836@mercury.worli> Hi All On Wednesday 17 October 2001 14:11, Remco wrote: > On 0, Danny Yoo wrote: > > About rejecting headers with the word "help" in them... er, I don't know > > about that one. What do other people think about this? > > I don't mind them (but heh, I'm not very active here at the moment). I'd > rather hit enter on two "help" messages per day than scare one person away > who'd gotten his first programming question refused because his subject > line was not informative enough. > > > In the terms of Lawrence Lessig's book "Code", I'd personally prefer that > > making good message headers (and making good questions) be something > > encouraged by community norms and not enforced by code. Just my thoughts > > on that. > > Well newbies here aren't really part of the programming community yet, are > they? They'll learn about that sort of thing in time. And I don't think we > should start filtering messages until society in general cleans up its act > > :-). Way to go...simply and beautifully put, Remco !!! Peace Steve -- ---------------------------------------------- Every oak tree started out as a couple of nuts who stood their ground. Anonymous ---------------------------------------------- From alan.gauld@bt.com Wed Oct 17 12:15:44 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 17 Oct 2001 12:15:44 +0100 Subject: [Tutor] Reuse output line on stdout Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BFFE@mbtlipnt02.btlabs.bt.co.uk> > Total Python newbie here. I have a loop that reads > and processes lines in a file. I want some feedback > so I have my script print the line number under > process to stdout. You mean something like: 000001: Here's some output 000003: Here's some for line 3 000012: Next line was 12 008732: Didn't do much with the previous stuff 009856: This will be the last line > several hundred thousand lines how do I get Python to > reuse the same line on stdout, i.e. I don't want a > newline/linefeed at the end of the output line, So instead of a sequence like above you only want a single line printed? Given the speed of processing you might be best to just print the last line! As a progress indicator maybe print a line of dots, something like: print "Processing file" linecount = 0 for line in f.readlines(): linecount += 1 if linecount%80 != 0 : print '.', # no newline else: print '.' # newline every 80 lines # do your processing here, including formnatting the # last line message print "\n %s" % message That will yield: Processing file: spam.txt .......................................................... ......................................... 143 : Did something on line Of course if it's thousands of lines long you might only want to print a dot every 50 lines or whatever scaling fdactor seems suitable - the idea is just some visible progress feedback to the user. I hope that helps, I'm not absolutely sure I understood the intent. Alan G From keith@kmantell.freeserve.co.uk Wed Oct 17 14:42:35 2001 From: keith@kmantell.freeserve.co.uk (keith@kmantell.freeserve.co.uk) Date: Wed, 17 Oct 2001 13:42:35 +0000 Subject: [Tutor] pymqe.pyd with Python 2.2 on WinNT Message-ID: <20011017134235.SBOP22056.fep05-svc.ttyl.com@localhost> I put pymqe.pyd ( a dll) in site-packages and got the following: >>> import pymqe Traceback (most recent call last): File "", line 1, in ? ImportError: DLL load failed: The specified module could not be found. If the file is not there I get: >>> import pymqe Traceback (most recent call last): File "", line 1, in ? ImportError: No module named pymqe Any bright ideas ? Thanks, Keith _______________________________________________________________________ Never pay another Internet phone bill! Freeserve AnyTime, for all the Internet access you want, day and night, only £12.99 per month. Sign-up at http://www.freeserve.com/time/anytime From dsh8290@rit.edu Wed Oct 17 16:31:13 2001 From: dsh8290@rit.edu (dman) Date: Wed, 17 Oct 2001 11:31:13 -0400 Subject: [Tutor] help ;-) [How to Ask Good Questions] In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Wed, Oct 17, 2001 at 01:08:29AM -0700 References: Message-ID: <20011017113111.A29508@harmony.cs.rit.edu> On Wed, Oct 17, 2001 at 01:08:29AM -0700, Danny Yoo wrote: ... | I'd be happy to add a link here to ESR's essay, but I should wait for a | consensus from the other tutor-admins before making the change to the | welcome text. | | | ESR's "How to Ask Questions The Smart Way" essay is a funny and | informative guide for newcomers to read before posting to a newsgroup or | mailing list. | | http://www.tuxedo.org/~esr/faqs/smart-questions.html | | I do agree with many of his points. The biggest qualm I have about it, | though, is that its language is really blunt. For example, calling people | "losers" for not knowing about the customs and habits of a community is | not the way I'd prefer to welcome people. *grin* We don't want to scare people aways. | However, I know he's using his language flamboyantly as a sort of "ha ha | only serious" thing --- his writing wouldn't be so compelling if it wasn't | so colorful. Also, I'm a bit hypersensitive about language and the | connotations of words, so perhaps I'm worrying about nothing. Maybe adding a comment on it, something to the effect that they shouldn't take his comments too seriously or personally and to ask their questions anyways. | About rejecting headers with the word "help" in them... er, I don't know | about that one. What do other people think about this? I think if it has _only_ the word help, then you might want to do this. If you don't do any filtering, that is fine by me too. I can do it on my end :-) (manually in my MUA). As you may have noticed, I haven't posted much recently. I've been rather swamped in schoolwork and other stuff. When I see a message with the subject "help", I assume that the question may be poorly asked, and/or a short eff-bot style answer will not suffice. If I have spare time, I really don't mind answering these at all, but lately I've just deleted the message without reading it. The moral of the story is that you are more likely to get answers if you use a better subject, but we won't kill you if you don't. -D From blakew@sonainnovations.com Wed Oct 17 18:05:57 2001 From: blakew@sonainnovations.com (Blake Winton) Date: Wed, 17 Oct 2001 13:05:57 -0400 Subject: [Tutor] help ;-) [How to Ask Good Questions] References: Message-ID: <00b601c1572e$002177b0$d6d35fd8@quintessential> Danny Yoo wrote: > I must apologize as well for being preachy in the last message. I didn't think you were particularly preachy... You did bring up a lot of good points, though. > I'd be happy to add a link here to ESR's essay, but I should wait for a > consensus from the other tutor-admins before making the change to the > welcome text. I'm not an admin, but I think a link would be okay, as long as it was explicitly mentioned that it's insulting to the sort of people who will probably be reading it. (Or maybe the people who won't be reading it... ;) > Also, I'm a bit hypersensitive about language and the > connotations of words, so perhaps I'm worrying about nothing. It did seem to be written for people who already follow its advice, or at least for hackers. > About rejecting headers with the word "help" in them... er, I don't know > about that one. What do other people think about this? I would say that if people don't want to answer them, they can filter the "help" messages out themselves. There are several levels of helper on the tutor list, with varying amounts of free time, and perhaps some of them will help the people no-one else does. Admittedly, I don't read most of the "help" messages, but they do pop up for a couple of seconds in my preview pane, so if it's something I am interested in, I'll get it out of my Deleted Items folder, and reply. > In the terms of Lawrence Lessig's book "Code", I'd personally prefer that > making good message headers (and making good questions) be something > encouraged by community norms and not enforced by code. Just my thoughts > on that. I would agree here, but for the fact that this can't be a community norm, since it only really applies to people who haven't read the list before. Sure, we could reply to everyone who posts a "help" message, and ask for more information, and hopefully they won't post a second, but I don't think I've seen more than four questions from anyone on the list, and I'm pretty sure I haven't seem more than one "help" question from any given person. (I'm hoping someone will dig through the archives to prove me wrong. ;) Perhaps just a link in the initial message saying something along the lines of "If your message had a subject line consisting only of the word 'help', you might not get a response. Please feel free to repost your question, but try to follow the guidelines in http://www.chiark.greenend.org.uk/~sgtatham/bugs.html or http://www.tuxedo.org/~esr/faqs/smart-questions.html." Later, Blake. From severinofer@recol.es Wed Oct 17 18:32:00 2001 From: severinofer@recol.es (Severino Fernandez) Date: Wed, 17 Oct 2001 19:32:00 +0200 Subject: [Tutor] (no subject) Message-ID: I would like to know where I can get the compile.py file for Windows, as the overall present link is apparently broken. Thank you. Severino Fernandez Instituto Nacional de Tecnica Aeroespacial Departamento de Observación de la Tierra, Teledetección y Aeronomía Carretera de Ajalvir, Km 4 28850 Torrejon de Ardoz Spain Tel +34 91 677 41 30 +34 91 677 41 90 +34 91 305 16 52 Fax +34 91 677 46 46 Email severinofer@recol.es From ak@silmarill.org Wed Oct 17 18:30:36 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Wed, 17 Oct 2001 13:30:36 -0400 Subject: [sill: Re: [Tutor] help ;-)] Message-ID: <20011017133036.A4533@sill.silmarill.org> --Boundary_(ID_NXf6AyRKpcZVraLYtVC+MQ) Content-type: text/plain; charset=us-ascii Content-transfer-encoding: 7BIT Content-disposition: inline Whoops.. I sent it to Danny Yoo instead of the list at first.. -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org --Boundary_(ID_NXf6AyRKpcZVraLYtVC+MQ) Content-type: message/rfc822 Date: Wed, 17 Oct 2001 05:14:27 -0400 Subject: Re: [Tutor] help ;-) In-reply-to: To: Danny Yoo Reply-to: ak@silmarill.org Message-id: <20011017051427.A1318@sill.silmarill.org> MIME-version: 1.0 Content-type: text/plain; charset=us-ascii Content-transfer-encoding: 7BIT Content-disposition: inline User-Agent: Mutt/1.3.20i References: <20011016160147.A28016@harmony.cs.rit.edu> On Tue, Oct 16, 2001 at 08:27:13PM -0700, Danny Yoo wrote: > It's my opinion that the educational culture in the United States does > real damage to people by not encouraging people encogh to practicing the > Process of discovering things. I feel that, instead, schools encourage > the impulse to depend on others for an answer, without asking how or why > that answer makes sense with what we already know. It's the path of least > friction: it's just easier to lure the "teacher" to give an answer, rather > than to discover it for oneself. This feeling seems echoed by John Holt's In my opinion, the problem is that Educational system, not just in US but generally in the world is absolutely counter-effective - it does everything wrong, from day one. First mistake is the tests - any sort of tests. The message is that you have to try to get the best grade with the least effort. Smartest kids will often learn less then others because they can get by with least knowledge. Second mistake is that things students do have next to nothing to do with real world. Third mistake is that teacher is the figure of authority. All of these come from the sad obsession with control that schools everywhere demonstrate - they would rather have some students learn a little and be correctly rated than have them learn a *lot* while their progress remains a mistery to the insitution. School is not the place for learning, it's the place for schooling and disciplining. Compulsion and learning are incompatible. The Fourth mistake is that every kid is put into the school and forced to attend whether he likes it or not - it looks good on paper - 100% of kids are in school, but how many are learning? The most tangible effect of modern schools is that students are taught to hate the process of aquiring knowledge - process that is inherently one of the most fascinating and enjoyable things you can do. This is sickening. What is the solution? Teachers must be freed from the responsibility of being a classroom cop. Students who don't want to study should be free to leave - they won't study either way. There must be no established program - learning should be a free process. There should be no tests integrated in the process, learning must be it's own and only reward. There is a school in UK that operates along these lines - Summerhill school. John Gotti (sp?) who was the teacher of the year in NY state, has been saying this for years. In fact he said that he sees no hope in current education system, that it's too inflexible to improve, and that the only hope for a reasonable education right now is home education. Oh, and you know why you can't open a textbook during the test? So it's easier for the teachers to rate us! For that reason alone 99% of "education" comes down to memorizing the formula. [snip] -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org --Boundary_(ID_NXf6AyRKpcZVraLYtVC+MQ)-- From dyoo@hkn.eecs.berkeley.edu Wed Oct 17 19:20:38 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 17 Oct 2001 11:20:38 -0700 (PDT) Subject: [Tutor] finding title tag (fwd) Message-ID: Dear Samir, I can't answer your question at the moment, so I'll forward this to the rest of the tutor list. It's usually a good idea to send messages to the whole list, so that many people have an opportunity to put their two cents in. ---------- Forwarded message ---------- Date: Wed, 17 Oct 2001 18:26:23 +1000 (EST) From: Samir Patel To: Danny Yoo Subject: Re: [Tutor] finding title tag (fwd) hi, well actually if u will look at my code i have implemented resursion in my program but using methods only....i am not comfortable with methods in a class and then applying recursion...... i have done recursion and i understand the concept..but bit confuse with python.....i have done java,C and stuff.... now as far as depth is concerned it will be given by the user and so it can be more then 3...that's the reason i have implemented rescursion .... i read that there's something called associative array ...can we implement that for link as key and title as the value...but again don't know how to actually implement that in a class..... in my case i will have to implement class as i have to use method start_tag() and end_tag().... i did tried to write a program using this methods and also implemented associative array...but can't apply recursion on them... #!/usr/local/bin/python import sys import urllib from formatter import NullFormatter from htmllib import HTMLParser class myparser(HTMLParser): def __init__(self): HTMLParser.__init__(self,NullFormatter()) self.linktext = {} self.url = None def start_a(self,attr): for key,val in attr: if key == 'title': self.url = val HTMLParser.save_bgn(self) def end_a(self): self.linktext[self.url] = HTMLParser.save_end(self) try: f = urllib.urlopen(sys.argv[1]) except IndexError: f = sys.stdin p = myparser() p.feed(f.read()) for link in p.linktext.keys(): print '-> ' , link , p.linktext[link] #sorry to bother u ... and thanx for your help.... above code is different from the code i have actually implemented....but i want to implement above code if possible but with recursion and associative array..... thanx a lot samir From szilard@int.com Wed Oct 17 21:44:11 2001 From: szilard@int.com (Szilard Bokros) Date: Wed, 17 Oct 2001 15:44:11 -0500 Subject: [Tutor] MySQL Message-ID: <3BCDED9B.B5566C3B@int.com> Hello, I would like to write a python script that reads two strings from a MySQL table, creates a directory with the second name, copies in a file, overwrites the first name in the database with the second name. My script looks like this: As a first step it would be eenough if I could just manipulate the database. Open it, get something fromit, overwrite something in it, etc... right now I reduced the script to a minimal version that does not work, somewhere here must be an error: #!/usr/local/python import MySQLdb db = MySQL.connect('localhost', 'eval', 'abrakadabra', 'Rumit') #sofar it seems to be OK result= db.query("""SELECT * FROM MyTableName""") which gives back an error message. So I have to do something before or after the result = ... line, or should I import something else? According to the O'Reilly MySQL book there is no need to set any cursor to execute querys. Sincere thanks for any clue. I know: there should be an examples directory in the MySQLdb mod I downloaded. There isn't. So thats it about clues from the author. Szilard From scarblac@pino.selwerd.nl Wed Oct 17 22:02:43 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 17 Oct 2001 23:02:43 +0200 Subject: [Tutor] MySQL (no answer yet) In-Reply-To: <3BCDED9B.B5566C3B@int.com>; from szilard@int.com on Wed, Oct 17, 2001 at 03:44:11PM -0500 References: <3BCDED9B.B5566C3B@int.com> Message-ID: <20011017230243.A5383@pino.selwerd.nl> On 0, Szilard Bokros wrote: (snip) > As a first step it would be eenough if I could just manipulate the > database. > Open it, get something fromit, overwrite something in it, etc... > right now I reduced the script to a minimal version that does not work, > somewhere here must be an error: > > #!/usr/local/python > import MySQLdb > db = MySQL.connect('localhost', 'eval', 'abrakadabra', 'Rumit') > #sofar it seems to be OK > result= db.query("""SELECT * FROM MyTableName""") > > which gives back an error message. I can't really help since I know nothing about MySQL, but... what is the error message? Your mail gives perfect explanation of what you're doing, just not of what goes wrong :) Python error messages usually contain a lot of useful information. -- Remco Gerlich From wheelege@tsn.cc Thu Oct 18 00:57:34 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Thu, 18 Oct 2001 09:57:34 +1000 Subject: [Tutor] help ;-) [How to Ask Good Questions] References: Message-ID: <012701c15767$a0d5d1e0$b4a616ca@ACE> From: "Danny Yoo" > > [Warning: no programming content again. This is more of a meta-question > thing. We'll probably stop this thread soon.] > Nah, don't do that - I think this thread is great :) > That magic person would either be Deirdre, Wesley, or me. *grin* I > haven't hear from Deirdre or Wesley for a while, so it looks like I'm > holding down the fort. I must apologize as well for being preachy in the > last message. > No need - preachiness is great when it comes from an intelligent and correct preacher. Here in Australia what you are saying is very true. Children in primary school are given maths 'tests' which consist only of 100 multiple choice questions, with no emphasis on proofs or any neccessity of understanding. > About getting your messages held: Mailman has some rules about filtering > messages that are sometimes a little oversensitive. At the same time, > they do appear to work most of the time: Spam flies at Tutor every day, > but the manager intercepts before it hits the rest of the list. I try to > laugh it off, but it's a little depressing to see how much automation goes > into attacking a community of volunteers. > I guess it's pointless here to suggest trying to stop the automation, with perhaps automation of our own (like letters to the spam companies, individuals) ? Most probably has already been attempted. > <...> > > I do agree with many of his points. The biggest qualm I have about it, > though, is that its language is really blunt. For example, calling people > "losers" for not knowing about the customs and habits of a community is > not the way I'd prefer to welcome people. *grin* > > <...> > > About rejecting headers with the word "help" in them... er, I don't know > about that one. What do other people think about this? > You bet. I think that the language he uses may scare people even more than not getting an answer to their question. By the same token should we block any mail which has html in it? I don't think so. It's not fair to the people who simply don't know, and can't know the standards which we would like. I think it would be a very poor turn for the worse to block e-mail which only has the word 'help' in it. They are usually the ones who need the help most. From sheila@thinkspot.net Thu Oct 18 01:49:08 2001 From: sheila@thinkspot.net (Sheila King) Date: Wed, 17 Oct 2001 17:49:08 -0700 Subject: [sill: Re: [Tutor] help ;-)] In-Reply-To: <20011017133036.A4533@sill.silmarill.org> References: <20011017133036.A4533@sill.silmarill.org> Message-ID: <903D9D079F@kserver.org> On Wed, 17 Oct 2001 13:30:36 -0400, Andrei Kulakov wrote about [sill: Re: [Tutor] help ;-)]: :Third mistake is that teacher :is the figure of authority. All of these come from the sad obsession with :control that schools everywhere demonstrate - they would rather have some :students learn a little and be correctly rated than have them learn a :*lot* while their progress remains a mistery to the insitution. School is :not the place for learning, it's the place for schooling and disciplining. Andrei, I agree with most of your post. In fact, some of the "mistakes" that you list are the reasons why I am no longer teaching high school. I'm still teaching, though, currently at the college level. I do take exception, however, to the passage I've quoted above. In fact, most of the fine teachers that I worked with in my 18 years as a high school teacher do not fit the description that you have posted above, and *I* certainly don't. Perhaps it is true for many, but it is certainly not true for all, and I don't even think it is true for most. Teaching in an educational system is very difficult, for many of the reasons you listed in your post. There are many things wrong about the way that the system works. However, I don't see any chance of the system changing dramatically any time soon, and someone is going to be in that classroom teaching those kids. Bad-mouthing those who choose to go in there and "fight the good fight", engaging in a difficult, conflicted, and thankless task, is certainly not going to encourage anyone trying to do so, to endure and persist. I really think that identifying the teachers themselves as one of the "mistakes" of the whole educational system, is unkind, uncharitable, and not on-target. Please re-think that part of your post. Overall, I have enjoyed reading most of the posts on this topic. I've been away from the Tutor list for a while (too busy), but glanced into this folder today, just to see what has been up lately. I especially enjoyed Danny Yoo's "rant". I think Danny was 100% on-target. Today I was telling my Math 105 students, how they need to think what everything *means*. Note (I told them) that I do NOT simply say, "For this type of problem, apply this technique, ...for this other type, apply this technique..." In MY class, I go into a great deal of motivation, try to demonstrate relationships, and give reasons why stuff behaves as it does. I tell the students, that they need to try to wrap their brains around these ideas so that when they encounter unfamiliar problems, they will be able to reason them out and think for themselves. I'm very big on problem solving. Unfortunately, yes, Andrei is right, that tests are a big mistake. It does encourage the students to try to "get by" with as little as possible. This and many other reasons contribute to why I'm not in the classroom right now with teenagers. I don't know how much longer I will even hold out at the college level. Maybe a few years. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From rick@niof.net Thu Oct 18 02:28:54 2001 From: rick@niof.net (Rick Pasotto) Date: Wed, 17 Oct 2001 21:28:54 -0400 Subject: [Tutor] MySQL In-Reply-To: <3BCDED9B.B5566C3B@int.com> References: <3BCDED9B.B5566C3B@int.com> Message-ID: <20011017212853.A27748@tc.niof.net> On Wed, Oct 17, 2001 at 03:44:11PM -0500, Szilard Bokros wrote: > Hello, > I would like to write a python script that reads two strings from a > MySQL table, > creates a directory with the second name, copies in a file, > overwrites the first name in the database with the second name. > My script looks like this: > > As a first step it would be eenough if I could just manipulate the > database. > Open it, get something fromit, overwrite something in it, etc... > right now I reduced the script to a minimal version that does not work, > somewhere here must be an error: > > #!/usr/local/python > import MySQLdb > db = MySQL.connect('localhost', 'eval', 'abrakadabra', 'Rumit') > #sofar it seems to be OK > result= db.query("""SELECT * FROM MyTableName""") > > which gives back an error message. > So I have to do something before or after the result = ... line, > or should I import something else? > According to the O'Reilly MySQL book there is no need to set any cursor > to execute querys. I think you are using an old book which references an older module that worked differently. Note that you have imported MySQLdb and not MySQL. This should work: import MySQLdb db = MyQSLdb.Connect(host='localhost', db='dbname', user='user', password='passwd') cursor = db.cursor() try: cursor.execute("""select * from tablename""") except SyntaxError,msg: raise "Problem!","Query description" + str(msg) if cursor.rowcount > 0: rows = cursor.fetchall() for row in rows: print row[0],row[1],row[2],.... else: print "no rows selected" -- You contend that I am wrong to teach my son science and philosophy; I believe you are wrong to teach yours Greek and Latin. Let us both follow the dictate of our conscience. Let us allow the law of responsibility to operate for our families. It will punish the one who is wrong. Let us not call in human law; it could well punish the one who is not wrong. -- Frédéric Bastiat (1801-1850) Rick Pasotto rickp@telocity.com http://www.niof.net From shalehperry@home.com Thu Oct 18 06:30:56 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Wed, 17 Oct 2001 22:30:56 -0700 (PDT) Subject: [Tutor] a nifty python example from the python list Message-ID: everything below is from another poster: I agree; you're already asking for trouble by duplicating the long list of attribute list and in the actual parameters where Tankungen are created, but if you create Tankungen in a lot of places, the readability might be worth it. Coincidentally, I wrote something this morning that might make your life easier, and posted it under the subject 'defstruct.py'. # I occasionally find myself writing code like the following: # class Point: # def __init__(self, x, y): # self.x = x # self.y = y # and that's the whole class. This little module lets me write the above code # as # Point = defstruct('x', 'y') # and have done with it. # # The name is taken from Common Lisp; the syntax is taken from MzScheme's # define-struct and is similar to the Common Lisp boa constructor syntax. # define-record-type from SRFI 9 is nasty and Scheme-specific enough that # I didn't use it. # # I hereby dedicate this code to the public domain and disavow any copyright # interest in it. # # -- Kragen Sitaker, 2001-10-16 def defstruct(*fields): class Struct: def __init__(self, *contents): if len(contents) != len(self.structfields): raise TypeError, ( "wrong number of arguments: expected %d %s, got %d" % (len(self.structfields), repr(self.structfields), len(contents))) for fieldnum in range(len(contents)): setattr(self, self.structfields[fieldnum], contents[fieldnum]) Struct.structfields = fields return Struct def test(): point = defstruct('x', 'y') p1 = point(1, 2) assert p1.x == 1 assert p1.y == 2 complex = defstruct('real', 'imag') assert point is not complex assert isinstance(p1, point) assert not isinstance(p1, complex) test() -- Kragen Sitaker Perilous to all of us are the devices of an art deeper than we possess ourselves. -- Gandalf the White [J.R.R. Tolkien, "The Two Towers", Bk 3, Ch. XI] --------------End of forwarded message------------------------- We have buried the putrid corpse of Liberty. -- Benito Mussolini From printers@sendme.cz Thu Oct 18 10:39:59 2001 From: printers@sendme.cz (A) Date: Thu, 18 Oct 2001 11:39:59 +0200 Subject: [Tutor] Python script engine Message-ID: <3BCEBF8F.32176.90A37A@localhost> Hello, In my application I would like to allow users to add/use basic python commands but I do not want users to change my code of application directly. For example my program expects telephone. number in format +442076812563 but a user sometimes may want to supply 0044 207 681 2563 (please note a blank). Then the user would need to use STRING.JOIN Python function to get from the user's input (0044 207 681 2563) the string that my program expects (+442076812563) Does anyone have any idea how to do that? Thank you for help Ladislav From tonycervone@netzero.net Thu Oct 18 10:40:37 2001 From: tonycervone@netzero.net (tonycervone) Date: Thu, 18 Oct 2001 05:40:37 -0400 Subject: [Tutor] printing a word in the second line of a text tile References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C003@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <001901c157b8$f27c0ea0$ab8af4d1@w9y5d5> This is a multi-part message in MIME format. ------=_NextPart_000_0016_01C15797.6A2D0CA0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I want to thank those who replied to my first question, how to print a = word in the first line of a text file. How about if I want to print a = word according to any location in the second line of a text. That is, I = want to read the first two lines of a text file, and then print the = first word of the second line of the file. i am using the following: inp =3D open( 'filename') line =3D inp.readlines() print =3D line.split()[position] and I get an " attributeError: split" error . thanks again. tony ----- Original Message -----=20 From: alan.gauld@bt.com=20 To: tonycervone@netzero.net=20 Sent: Thursday, October 18, 2001 4:27 AM Subject: RE: [Tutor] printing a word in a line Alan, after entering the first line of your script, I get a "name = error: there is no variable named popen" Sorry, typo. It should be 'open' not 'popen' BTW thanks for the book feedback, its always welcome.=20 I'm planning a second edition after I finish my current=20 book late next year, so I will include some stuuff on=20 using glob and navigating directories etc. I already planned on some web programming stuff and=20 more on GUIs. Alan G ------=_NextPart_000_0016_01C15797.6A2D0CA0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I want to thank those who replied to my = first=20 question, how to print a word in the first line of a text file. How = about if I=20 want  to print a word according to any location in the second line = of =20 a text. That is, I want to read the first two lines of a text file, and = then=20 print the  first word of the second line of the file. i am using = the=20 following:
 
inp =3D open( 'filename')
line =3D inp.readlines()
print =3D = line.split()[position]
 
and I get an " attributeError: split" = error .=20 thanks again. tony
 
 
----- Original Message -----
From:=20 alan.gauld@bt.com
Sent: Thursday, October 18, = 2001 4:27=20 AM
Subject: RE: [Tutor] printing a = word in a=20 line

Alan, after entering the first line = of your=20 script, I get a "name error: there is no variable named = popen"
 
Sorry, typo. It should be 'open' not=20 'popen'
 
BTW thanks for the book feedback, its = always=20 welcome.
I'm planning a second edition after I = finish my=20 current
book late next year, so I will include = some stuuff=20 on
using glob and navigating directories=20 etc.
 
I already planned on some web programming = stuff and=20
more on GUIs.
 
Alan G
 
------=_NextPart_000_0016_01C15797.6A2D0CA0-- ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From scarblac@pino.selwerd.nl Thu Oct 18 11:08:33 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 18 Oct 2001 12:08:33 +0200 Subject: [Tutor] printing a word in the second line of a text tile In-Reply-To: <001901c157b8$f27c0ea0$ab8af4d1@w9y5d5>; from tonycervone@netzero.net on Thu, Oct 18, 2001 at 05:40:37AM -0400 References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C003@mbtlipnt02.btlabs.bt.co.uk> <001901c157b8$f27c0ea0$ab8af4d1@w9y5d5> Message-ID: <20011018120833.A6238@pino.selwerd.nl> On 0, tonycervone wrote: > I want to thank those who replied to my first question, how to print a word in the first line of a text file. How about if I want to print a word according to any location in the second line of a text. That is, I want to read the first two lines of a text file, and then print the first word of the second line of the file. i am using the following: > > inp = open( 'filename') > line = inp.readlines() > print = line.split()[position] > > and I get an " attributeError: split" error . thanks again. tony "print = " isn't allowed, print is a reserver word. You probably wrote it without the =. inp.readlines() returns a list of lines. split() is something you can do on an individual line. So you're almost there. What you wanted is read a single line, the first one. that's readline, not readlines. inp = open('filename') line = inp.readline() print line.split()[position] If you want to use readlines, it's read inp = open('filename') lines = inp.readlines() print lines[0].split()[position] But it's a waste to read in all those other lines if you only need the first. -- Remco Gerlich From ak@silmarill.org Thu Oct 18 12:46:56 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Thu, 18 Oct 2001 07:46:56 -0400 Subject: [sill: Re: [Tutor] help ;-)] In-Reply-To: <903D9D079F@kserver.org> References: <20011017133036.A4533@sill.silmarill.org> <903D9D079F@kserver.org> Message-ID: <20011018074656.A8082@sill.silmarill.org> On Wed, Oct 17, 2001 at 05:49:08PM -0700, Sheila King wrote: > On Wed, 17 Oct 2001 13:30:36 -0400, Andrei Kulakov > wrote about [sill: Re: [Tutor] help ;-)]: > > :Third mistake is that teacher > :is the figure of authority. All of these come from the sad obsession with > :control that schools everywhere demonstrate - they would rather have some > :students learn a little and be correctly rated than have them learn a > :*lot* while their progress remains a mistery to the insitution. School is > :not the place for learning, it's the place for schooling and disciplining. > > Andrei, > > I agree with most of your post. In fact, some of the "mistakes" that you > list are the reasons why I am no longer teaching high school. I'm still > teaching, though, currently at the college level. > > I do take exception, however, to the passage I've quoted above. In fact, > most of the fine teachers that I worked with in my 18 years as a high > school teacher do not fit the description that you have posted above, > and *I* certainly don't. Perhaps it is true for many, but it is > certainly not true for all, and I don't even think it is true for most. But note, I didn't even say the word "teacher"! This is not the first time I make this sort of post, and I learned by my mistakes.. Apparently, next time I'll have to include an outright disclaimer that expicitly excludes any blame from the teacher. The problem lies with the system, not with the teachers. That said, most teachers in HS are horrible, and only very few are trying to do something real. I'm not sure which is worse, watching a drone reading from a textbook or watching a great teacher trying to do his job as well as possible and failing miserably. On this point, I agree with John Gotti (I hope I got his name right, all google comes up with is the mobster.. symptom of the disease, eh?). Being a good teacher is, in my opinion, counter-productive - you help keep up the system that is inherently hopeless. The guy pretty much gave up and started from a scratch in a private school somewhere in Ohio.. On the other hand, maybe I was just unlucky. I was in a huge school in brooklyn, and I remember 3 good teachers out of maybe 3 dozens that I had there. They taught me nothing, I mean the good ones. I just wasn't accustomed to learning. Same thing in Russia, where I was a student before I moved to brooklyn. You know many people here blame the liberal changes in ed. system with multiple choice questions, lowering of standards, etc etc. Russian education is much more profound, you have to do every proof in detail, everybody starts chemistry and rather advanced physics grade 5? or so, and it's even worse than here - nearly all of my classmates there hated the school with passion. Grades on average were very low, most everyone was copying from each other, and so forth. > > Teaching in an educational system is very difficult, for many of the > reasons you listed in your post. There are many things wrong about the > way that the system works. However, I don't see any chance of the system > changing dramatically any time soon, and someone is going to be in that > classroom teaching those kids. Bad-mouthing those who choose to go in > there and "fight the good fight", engaging in a difficult, conflicted, > and thankless task, is certainly not going to encourage anyone trying to > do so, to endure and persist. Yes, I know that except that 1. i wasn't badmouthing them. and 2. I think their efforts, however noble in spirit, are counter-effective. > > I really think that identifying the teachers themselves as one of the > "mistakes" of the whole educational system, is unkind, uncharitable, and > not on-target. Please re-think that part of your post. Oh I went back now and I think you're referring to me saying that a teacher is a figure of authority. It's a fact, not my judgement. He tells you what to study, when to study, gives you a hallway pass if he deems it necessary, and so on. The system corrupts the teacher just as badly as the student. > > Overall, I have enjoyed reading most of the posts on this topic. I've > been away from the Tutor list for a while (too busy), but glanced into > this folder today, just to see what has been up lately. I especially > enjoyed Danny Yoo's "rant". I think Danny was 100% on-target. Yeah, I agree with him too, but I think he blames all the troubles on relatively recent liberalization of the system, while in my experience the old style of teaching is even worse. > > Today I was telling my Math 105 students, how they need to think what > everything *means*. Note (I told them) that I do NOT simply say, "For > this type of problem, apply this technique, ...for this other type, > apply this technique..." In MY class, I go into a great deal of > motivation, try to demonstrate relationships, and give reasons why stuff > behaves as it does. I tell the students, that they need to try to wrap > their brains around these ideas so that when they encounter unfamiliar > problems, they will be able to reason them out and think for themselves. > I'm very big on problem solving. That's the right direction, but just not enough. It's sort of like walking into a pen with slaves and telling them "keep working, but think free thoughts, about mountain climbing, dewy forests and such". > > Unfortunately, yes, Andrei is right, that tests are a big mistake. It > does encourage the students to try to "get by" with as little as > possible. This and many other reasons contribute to why I'm not in the > classroom right now with teenagers. I don't know how much longer I will > even hold out at the college level. Maybe a few years. > > -- > Sheila King > http://www.thinkspot.net/sheila/ > http://www.k12groups.org/ > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From szilard@int.com Thu Oct 18 16:43:30 2001 From: szilard@int.com (BackupAdmin) Date: Thu, 18 Oct 2001 10:43:30 -0500 Subject: [Tutor] Re: Tutor digest, Vol 1 #1146 - 11 msgs References: Message-ID: <001801c157eb$a38814a0$ca65c1cf@easyrider> > > This should work: > > import MySQLdb > db = MyQSLdb.Connect(host='localhost', db='dbname', > user='user', password='passwd') > cursor = db.cursor() > try: > cursor.execute("""select * from tablename""") > except SyntaxError,msg: > raise "Problem!","Query description" + str(msg) > if cursor.rowcount > 0: > rows = cursor.fetchall() > for row in rows: > print row[0],row[1],row[2],.... > else: > print "no rows selected" Thanks, this brings me closer to the solution. The db='dbname' should be the last among the variables othervise it gives back an error message to me. This is fine. The problem is with "execute ". There is no real problem untill the line 6. Now the errormessage is: Traceback (innermost last): File "./myscarnacnew.py", line 6, in ? cursor.execute("""select * from Directories""") AttributeError: execute The Directories is a valid table name. The problem is with execute: #!/usr/bin/python import MySQLdb argggh = MySQLdb.connect('localhost', 'eval', 'abrakadabra') cursor = argggh.cursor cursor.execute("""use Timur""") argggh.close Traceback (innermost last): File "./myscarnacnew.py", line 5, in ? cursor.execute("""use Timur""") AttributeError: execute There is no execute method for the cursor? how else can I issue querrys? Szilard From rick@niof.net Thu Oct 18 17:17:38 2001 From: rick@niof.net (Rick Pasotto) Date: Thu, 18 Oct 2001 12:17:38 -0400 Subject: [Tutor] Re: Tutor digest, Vol 1 #1146 - 11 msgs In-Reply-To: <001801c157eb$a38814a0$ca65c1cf@easyrider> References: <001801c157eb$a38814a0$ca65c1cf@easyrider> Message-ID: <20011018121738.B27748@tc.niof.net> On Thu, Oct 18, 2001 at 10:43:30AM -0500, BackupAdmin wrote: > > #!/usr/bin/python > import MySQLdb > argggh = MySQLdb.connect('localhost', 'eval', 'abrakadabra') > cursor = argggh.cursor This should be: cursor = arggh.cursor() You need to *call* (which is what the parentheses does) the 'cursor' method of the 'argggh' instance instead of just assigning it to a variable. -- Our doctrine is based on private property. Communism is based on systematic plunder, since it consists in handing over to one man, without compensation, the labor of another. If it distributed to each one according to his labor, it would, in fact, recognize private property and would no longer be communism. -- Frédéric Bastiat (1801-1850) Rick Pasotto rickp@telocity.com http://www.niof.net From jeff@ccvcorp.com Thu Oct 18 17:44:36 2001 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu, 18 Oct 2001 09:44:36 -0700 Subject: [Tutor] printing a word in the second line of a text file References: Message-ID: <3BCF06F4.F00DE7A3@ccvcorp.com> > tonycervone asked: > > ... How about if I want to print a > word according to any location in the second line of a text? ... > > and Remco Gerlich replied: > > inp.readlines() returns a list of lines. split() is something you can do on > an individual line. So you're almost there. > > What you wanted is read a single line, the first one. that's readline, not > readlines. > > inp = open('filename') > line = inp.readline() > print line.split()[position] > > If you want to use readlines, it's read > > inp = open('filename') > lines = inp.readlines() > print lines[0].split()[position] > Now, in order to read a word from the second line, or whatever line number you want... you can do this in one of two ways: ---- example 1 ------ lineno = 2 # this is the line you want to read a word from... inp = open('filename') for n in range(lineno): #loop through this a number of times equal to lineno ... line = inp.readline() # reading a single line (lineno times) print line.split()[position] ---- example 2 ------ inp = open('filename') lines = inp.readlines() # read in the entire file myline = lines[lineno - 1] # grab the line we're interested in print myline.split()[position] ----------------------- Note that in example 2, when I go to grab the line I want, I use (lineno - 1)--this is because lists use 0-based indexing, instead of the 1-based counting that humans normally use (and yes, there *are* good reasons for this, but I won't go into them here). Example 1 uses a fairly slow loop-and-read process, while example 2 reads the entire file in one gulp. As a result, example 2 will be quicker and probably more efficient for small files, or files that you want to look near the *end* of. Example 1 will be better for reading lines near the beginning of large files. Of course, exactly what "small" and "large" means, will depend on your processor, available memory, disk, etc... ;) (I'd use example 2 in strong preference to example 1, unless you're always grabbing from the first line or two, or are *very* short on memory... ) Jeff Shannon Technician/Programmer Credit International From wheelege@tsn.cc Fri Oct 19 00:52:32 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Fri, 19 Oct 2001 09:52:32 +1000 Subject: [sill: Re: [Tutor] help ;-)] References: <20011017133036.A4533@sill.silmarill.org> <903D9D079F@kserver.org> <20011018074656.A8082@sill.silmarill.org> Message-ID: <00b601c1582f$f4e8f6e0$a5a616ca@ACE> > <...> > > > > > Today I was telling my Math 105 students, how they need to think what > > everything *means*. Note (I told them) that I do NOT simply say, "For > > this type of problem, apply this technique, ...for this other type, > > apply this technique..." In MY class, I go into a great deal of > > motivation, try to demonstrate relationships, and give reasons why stuff > > behaves as it does. I tell the students, that they need to try to wrap > > their brains around these ideas so that when they encounter unfamiliar > > problems, they will be able to reason them out and think for themselves. > > I'm very big on problem solving. > > That's the right direction, but just not enough. It's sort of like walking > into a pen with slaves and telling them "keep working, but think free > thoughts, about mountain climbing, dewy forests and such". > And how would you solve these 'problems'? I think that Sheila's method of teaching sounds great. From wheelege@tsn.cc Fri Oct 19 01:57:02 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Fri, 19 Oct 2001 10:57:02 +1000 Subject: [sill: Re: [Tutor] help ;-)] References: <20011017133036.A4533@sill.silmarill.org> <903D9D079F@kserver.org> <20011018074656.A8082@sill.silmarill.org> <00b601c1582f$f4e8f6e0$a5a616ca@ACE> <20011018200153.A14452@sill.silmarill.org> Message-ID: <00be01c15838$f73f05c0$a5a616ca@ACE> > > > > And how would you solve these 'problems'? I think that Sheila's method of > > teaching sounds great. > > I already said in previous message, no tests, teacher has no authority, no > program, students must be free to do anything they want whenever they > want. Teacher stands by and helps when help is requested. Oh, and no > tests. There's a Summerhill school in britain that worked like that for > decades, and it's been doing well (and it's still working, it's a private > school). Gotti, teacher of the year from New York said that he sees no > hope in current education system and his opinion is that the only way to > get reasonably decent education is through home schooling. > Surely that wouldn't work for public schools. The children would just act like children - they would do no work, get no education. Come to school, hang out with friends, go home again. I do agree that the system is broken, and that people are being rewarded for how many answers they can sponge up and hold at a time, but I don't think that is the answer. Believe it or not, a huge portion of the population do not want to learn. Are you sayin that we simply shouldn't teach them? I myself was a part rebellious in my high school lifetime, but during the end when things started to get serious (last two years) I knuckled down and started appreciating knowledge for what it is, and also appreciating logic plus problem solving. I think that without this system which persisted with me, to continually nag and even oppress me into learning, I would not be the person I am today. From wheelege@tsn.cc Fri Oct 19 02:19:40 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Fri, 19 Oct 2001 11:19:40 +1000 Subject: [Tutor] Python script engine References: <3BCEBF8F.32176.90A37A@localhost> Message-ID: <013901c1583c$22126f00$a5a616ca@ACE> > Hello, > In my application I would like to allow users to add/use basic > python commands but I do not want users to change my code of > application directly. > Hi :) This sounds like you want to take raw_input then eval or exec it...but that can lead to problems like malicious users killing your server, so why not take a different approach? > > For example my program expects > telephone. number in format > +442076812563 > but a user sometimes may want to > supply > 0044 207 681 2563 > (please note a blank). > Then the user would need > to use STRING.JOIN Python function to get from the user's input > (0044 207 681 2563) the string that my program expects > (+442076812563) > > Does anyone have any idea how to do that? > Well, you could think about all the ways that a user can input your string and then your program can format it itself. Like if there is a space in the string, remove all the spaces. If somebody puts brackets in, then remove them. If there is no plus sign, add one. They aren't very difficult compared to the sort of checking you would have to do if you went with the user minupulating his/her own string...and the user doensn't need to know python either :) HTH, Glen From toodles@yifan.net Fri Oct 19 03:39:56 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Fri, 19 Oct 2001 10:39:56 +0800 Subject: [Tutor] Python script engine References: <3BCEBF8F.32176.90A37A@localhost> <013901c1583c$22126f00$a5a616ca@ACE> Message-ID: <000f01c15847$582cae10$0300a8c0@sun> ----- Original Message ----- From: "Glen Wheeler" To: Sent: Friday, October 19, 2001 9:19 AM Subject: Re: [Tutor] Python script engine > > > > Hello, > > In my application I would like to allow users to add/use basic > > python commands but I do not want users to change my code of > > application directly. > > > > Hi :) This sounds like you want to take raw_input then eval or exec > it...but that can lead to problems like malicious users killing your server, > so why not take a different approach? *nod* Perhaps this is where Restricted Execution (module rexec) would come in handy. I've never used it myself, but it restricts just what objects the user has access to. Andrew Kuchling has a HOWTO here: http://www.python.org/doc/howto/rexec/ Just some thoughts...HTH! Andrew > > > > > For example my program expects > > telephone. number in format > > +442076812563 > > but a user sometimes may want to > > supply > > 0044 207 681 2563 > > (please note a blank). > > Then the user would need > > to use STRING.JOIN Python function to get from the user's input > > (0044 207 681 2563) the string that my program expects > > (+442076812563) > > > > Does anyone have any idea how to do that? > > > > Well, you could think about all the ways that a user can input your string > and then your program can format it itself. Like if there is a space in the > string, remove all the spaces. If somebody puts brackets in, then remove > them. If there is no plus sign, add one. They aren't very difficult > compared to the sort of checking you would have to do if you went with the > user minupulating his/her own string...and the user doensn't need to know > python either :) > > HTH, > Glen > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From Mercedes@kadsolutions.com Fri Oct 19 04:25:07 2001 From: Mercedes@kadsolutions.com (Mercedes) Date: Thu, 18 Oct 2001 22:25:07 -0500 Subject: [Tutor] xml to a text file Message-ID: <002801c1584d$b89ce2a0$6601a8c0@i1h8r5> This is a multi-part message in MIME format. ------=_NextPart_000_0020_01C15823.BDCE5440 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable HI, I am trying to process an xml file using python, I wrote a parser = to do this but I wish to proceed and make it into a text file = (somthing.text) is this possible and how do I this? Mercedes ------=_NextPart_000_0020_01C15823.BDCE5440 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
HI, I am trying to process an xml file = using=20 python,  I wrote a parser to do this but I wish to proceed and make = it into=20 a text file  (somthing.text) is this possible and how do  I=20 this?
Mercedes
------=_NextPart_000_0020_01C15823.BDCE5440-- From ignacio@openservices.net Fri Oct 19 04:38:30 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Thu, 18 Oct 2001 23:38:30 -0400 (EDT) Subject: [Tutor] xml to a text file In-Reply-To: <002801c1584d$b89ce2a0$6601a8c0@i1h8r5> Message-ID: On Thu, 18 Oct 2001, Mercedes wrote: > HI, I am trying to process an xml file using python, I wrote a parser to do this but I wish to proceed and make it into a text file (somthing.text) is this possible and how do I this? > Mercedes Well, XML files are already text files, so you'll have to be a little more specific than that. -- Ignacio Vazquez-Abrams "As far as I can tell / It doesn't matter who you are / If you can believe there's something worth fighting for." - "Parade", Garbage From sheila@thinkspot.net Fri Oct 19 06:19:13 2001 From: sheila@thinkspot.net (Sheila King) Date: Thu, 18 Oct 2001 22:19:13 -0700 Subject: [sill: Re: [Tutor] help ;-)] In-Reply-To: <20011018074656.A8082@sill.silmarill.org> References: <20011017133036.A4533@sill.silmarill.org> <903D9D079F@kserver.org> <20011018074656.A8082@sill.silmarill.org> Message-ID: <61C326359E@kserver.org> This is my final post in this thread on the Tutor Mailing list. I apologize in advance, for an off-topic post. For those who would like to continue in this discussion, either email or the newsgroup k12.chat.teacher would be appropriate venues. If interested, Read on! On Thu, 18 Oct 2001 07:46:56 -0400, Andrei Kulakov wrote about Re: [sill: Re: [Tutor] help ;-)]: :On Wed, Oct 17, 2001 at 05:49:08PM -0700, Sheila King wrote: :> On Wed, 17 Oct 2001 13:30:36 -0400, Andrei Kulakov :> wrote about [sill: Re: [Tutor] help ;-)]: :> :> :Third mistake is that teacher :> :is the figure of authority. All of these come from the sad obsession with :> :control that schools everywhere demonstrate - they would rather have some :> :students learn a little and be correctly rated than have them learn a :> :*lot* while their progress remains a mistery to the insitution. School is :> :not the place for learning, it's the place for schooling and disciplining. :> :> Andrei, :> :> I agree with most of your post. In fact, some of the "mistakes" that you :> list are the reasons why I am no longer teaching high school. I'm still :> teaching, though, currently at the college level. :> :> I do take exception, however, to the passage I've quoted above. In fact, :> most of the fine teachers that I worked with in my 18 years as a high :> school teacher do not fit the description that you have posted above, :> and *I* certainly don't. Perhaps it is true for many, but it is :> certainly not true for all, and I don't even think it is true for most. : :But note, I didn't even say the word "teacher"! Uh, please examine the quote above again. The word "teacher" is most definitely in the quote from your message. ...... :The problem lies with the system, not with the teachers. That said, most :teachers in HS are horrible, and only very few are trying to do something :real. I'm not sure which is worse, watching a drone reading from a :textbook or watching a great teacher trying to do his job as well as :possible and failing miserably. Sorry about the misunderstanding. It was not clear to me from your post, that you meant the "teacher as authority figure" being the problem. I will agree that it is easier to do the job, if the students see you as a partner to help them learn. For example, I taught AP Calculus for 8 or 9 years. (I'm not sure if you are familiar with the College Board's Advanced Placement program? http://www.collegeboard.org/ap/) What was nice about this: I was like my students' coach, to help them prepare for passing the AP exam at the end of the year. Having students take an exam prepared by an agency outside of the school system, a quality, difficult exam, with real benefits to passing, puts a whole new light on the teacher/student relationship. For those students who really want to pass the exam, they are much more willing to put up with difficult requirements from the teacher, if the teacher can cast it in the light of "stuff that is necessary in order to help you prepare for this exam". As for "a great teacher trying to do his job and failing miserably", you curiously omit from your post another possibility: A great teacher trying to do his job and having a reasonable amount of success. Or even a fairly large amount of success. I had a great deal of success in my many years as a teacher. If I had not, I certainly wouldn't have continued doing it for as long as I did. You seem to see the whole system as a complete and abysmal failure. I'm not sure what has affected you to see the system in this way, and I would agree that the system is broken and has many, many problems, but it does have successes too, many of them every year. Telling good teachers in the system that they are part of the problem because they are propping the system up and enabling it to continue...I don't think this is worthwhile, effective or considerate to those doing the job. I realize this is your opinion, that it is in line with Mr. John Taylor Gatto's, and that you have a right to express it. But, I disagree that it will do any good, and it certainly won't help those good teachers who hear it, IMHO. :On this point, I agree with John Gotti (I hope I got his name right, all :google comes up with is the mobster.. symptom of the disease, eh?). Being :a good teacher is, in my opinion, counter-productive - you help keep up :the system that is inherently hopeless. The guy pretty much gave up and :started from a scratch in a private school somewhere in Ohio.. As mentioned above, his name is John Taylor Gatto. I have his book _Dumbing Us Down: The Hidden Curriculum of Compulsory Schooling_ right here. The back cover of the book says (in part): "In his 26 years of teaching, John Taylor Gatto has found that independent study, community service, large doses of solitude, and a thousand different apprenticeships with adults of all walks of life are the keys to helping children break the thrall of our conforming society. For the sake of our children and our communities, John Taylor Gatto urges all of us to get schools out of the way and find ways to re-engage children and families in actively controlling our culture, economy, and society." Clearly Mr. Gatto has many good ideas. However, his idea that all good teachers should leave the school system, because the system needs to collapse is one I'm not sure I can agree with. I do think that ultimately some school systems (selected school districts around the country) are going to collapse. I do know of schools nearby where little learning goes on, and teachers teach to classes with high absentee rates and dumb down the material just to get by and say they've gotten through something. I think this isn't universal, though. In the cases I know of, it is poor, urban schools that have this problem. The school district where I live and my children attend is in an affluent, upper-middle-class, professional neighborhood. They are excellent schools with pretty good teachers and my children seem to learn a lot there. ...... :> I really think that identifying the teachers themselves as one of the :> "mistakes" of the whole educational system, is unkind, uncharitable, and :> not on-target. Please re-think that part of your post. : :Oh I went back now and I think you're referring to me saying that a :teacher is a figure of authority. It's a fact, not my judgement. He tells :you what to study, when to study, gives you a hallway pass if he deems it :necessary, and so on. The system corrupts the teacher just as badly as the :student. That is the part I was referring to. While the teacher is in control in most classrooms, it certainly doesn't have to be that way. Anyhow, I don't see anything wrong with a designated body of knowledge that should be acquired. What would be better, though, in my opinion is this: Schools do not issue grades. Instead there is an independent "certification board", with tests that you must pass in order to earn a certification. Schools would be independent of the certification process. They would simply teach you the stuff you needed in order to pass whatever certification(s) you were interested in earning. (Sort of like law school prepares you for passing the Bar Exam, although I'd expect the schools in my scenario to match their curriculum and activities more closely to the certification exam content than law school tends to match the Bar Exam?) In this way, the only reason for being in the school, would be because you wanted to prepare for something by an outside agency. Well, it's a thought, anyway. I will say this about schooling: I love learning. And I actually like being a student, even in a school system situation. I know some people hate it. But it never bothered me. I have many friends and family whom it has bothered, though. And I sympathize with them. And for those people for whom the school system does not work, I think we need to find another solution. Because many of them WANT to learn, but the system doesn't work for them. In any case, within the last year or two, I've become more interested, personally, in web design and programming. This past year I started learning Python. I was really enjoying the stuff I was learning. (Doing it via online resources, books and the Python community, as most here on this list do.) My job as a teacher tired me. It required a lot of my physical, mental and emotional resources in addition to great gobs of my personal time. And I could see that I was exerting a lot of my resources trying to get people who didn't want to learn math to learn math. And ending up having less time and energy for me to do the learning that *I* was interested in. I finally got tired of it. I didn't want to be the one trying to force these kids to learn stuff they didn't want to learn at the expense of my not being able to learn things *I* wanted to learn. So I completely appreciate everything about the compulsory schooling and forcing kids to learn. I'm familiar with SummerHill and Sudbury Valley and schools of that type. And in an ideal world, that would be best. I just don't see how the public system could really go to that. Dunno. ...... :> Today I was telling my Math 105 students, how they need to think what :> everything *means*. Note (I told them) that I do NOT simply say, "For :> this type of problem, apply this technique, ...for this other type, :> apply this technique..." In MY class, I go into a great deal of :> motivation, try to demonstrate relationships, and give reasons why stuff :> behaves as it does. I tell the students, that they need to try to wrap :> their brains around these ideas so that when they encounter unfamiliar :> problems, they will be able to reason them out and think for themselves. :> I'm very big on problem solving. : :That's the right direction, but just not enough. It's sort of like walking :into a pen with slaves and telling them "keep working, but think free :thoughts, about mountain climbing, dewy forests and such". I really think that your analogy is faulty. The students in my Math 105 class have a variety of reasons for being there (remember, it is a college class). For some of them, it may just be a general ed course and the last math class they have to take. Just passing will be good enough for them, and they don't really care if they learn and retain the material at all. They just need to get a passing grade, however one might manage that. Others in the class think they are going to be engineers. Considering what they have ahead of them, they'd darn well better WANT to learn the stuff I'm teaching them, or else they'd better choose a different career path. For those who couldn't care less about the content of my course, what I am doing above is like a noisy wind blowing past them and they don't hear any meaning in it. For those who WANT to learn what I am teaching them, what I am saying is good advice, a coaching strategy that may help them down the line with other courses as well. I really encourage anyone who is seriously interested in continuing a discussion along these lines, to visit the newsgroup k12.chat.teacher. This type of stuff comes up there often, and there are many intelligent, dedicated teachers there (and also non-teachers who vary from trolls to interested friends of educators), who would be willing to discuss this type of stuff yet one more time. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From agauld@crosswinds.net Fri Oct 19 07:50:25 2001 From: agauld@crosswinds.net (agauld@crosswinds.net) Date: Fri, 19 Oct 2001 07:50:25 +0100 Subject: [Tutor] My crosswinds site is dead again Message-ID: <06570545344720@mailth4.freenet.co.uk> Hi folks, It looks like crosswinds has died again and my tutor is offline. If anyone sees anyone anywhere asking where it is can you please point them at the new site: http://www.freenetpages.co.uk/hp/alan.gauld/ I'm gonna start the painful process of notifying all the linking sites that that will be the new master address. When crosswinds does come back to life I'll try fitting auto redirection to the index, contents and intro pages... Thanks and sorry for taking up tutor bandwidth but a lot of my sites users seem to live here! :-) Alan G. From alan.gauld@bt.com Fri Oct 19 12:44:05 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 19 Oct 2001 12:44:05 +0100 Subject: [sill: Re: [Tutor] help ;-)] Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C006@mbtlipnt02.btlabs.bt.co.uk> > I agree with most of your post. Me too, but less than you maybe :-) > ... tests are a big mistake. It > does encourage the students to try to "get by" > with as little as possible. I'm not sure I agree that tets per se are bad. What I don't like is the current trend to multi-choice tests which can be passed in theory by pure luck! Especially when out of 5 choices there will usually be at least 1 that's obviously dumb, another that's dumb with even basic understanding - which leaves a 30% chance of getting it right. Not much of a test. Good tests, which really do test understanding mimic the real world which is full of tests: "Here's a deadline, if you don't meet it you're fired and if you do meet it and it doesn't work then you're still fired." That survival ethic has to be taught to kids somehow and tests are a relatively gentle way of doing it. After all the important part of any education system is not the imparting of knowledge but the training in new behavioural patterns - the habits of effective study, the ability to crystalize and communicate ideas, the efficient and focused achievement of goals etc. Just my 2 cents, alan g. PS Shouldn't this discussion be on the edu-sig mailing list rather than tutor? :-) From alan.gauld@bt.com Fri Oct 19 12:49:42 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 19 Oct 2001 12:49:42 +0100 Subject: [Tutor] printing a word in the second line of a text tile Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C007@mbtlipnt02.btlabs.bt.co.uk> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C15894.2404C120 Content-Type: text/plain; charset="iso-8859-1" inp = open( 'filename') line = inp.readlines() print = line.split()[position] and I get an " attributeError: split" error . thanks again. tony Because you are now reading lines, plural, so the variable line is actually a list. But split is a method of string objects. So you need to extract the string from the list either by iterating over the list: lines = inp.readlines() for line in lines: # do something here Or by indexing for a spercific position: print line[linenumber].split()[position] HTH, Alan G. ------_=_NextPart_001_01C15894.2404C120 Content-Type: text/html; charset="iso-8859-1"
inp = open( 'filename')
line = inp.readlines()
print = line.split()[position]
 
and I get an " attributeError: split" error . thanks again. tony 
Because you are now reading lines, plural, so
the variable line is actually a list. But split
is a method of string objects. 
 
So you need to extract the string from the list
either by iterating over the list:
 
lines = inp.readlines()
for line in lines: 
    # do something here
 
Or by indexing for a spercific position:
 
print line[linenumber].split()[position]
 
HTH,
 
Alan G.
 
------_=_NextPart_001_01C15894.2404C120-- From ak@silmarill.org Fri Oct 19 13:03:26 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Fri, 19 Oct 2001 08:03:26 -0400 Subject: [sill: Re: [Tutor] help ;-)] In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C006@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C006@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20011019080326.A16495@sill.silmarill.org> On Fri, Oct 19, 2001 at 12:44:05PM +0100, alan.gauld@bt.com wrote: > > I agree with most of your post. > > Me too, but less than you maybe :-) > > > ... tests are a big mistake. It > > does encourage the students to try to "get by" > > with as little as possible. > > I'm not sure I agree that tets per se are bad. > What I don't like is the current trend to > multi-choice tests which can be passed in theory > by pure luck! Especially when out of 5 choices > there will usually be at least 1 that's obviously > dumb, another that's dumb with even basic > understanding - which leaves a 30% chance of > getting it right. Not much of a test. I first studied in Russia, where there were no multiple-choice tests, then in US where they're abundant. In my experience, both approaches are just as bad. In fact, the Russian tests are even worse, because they annoy students more, while there isn't any win as far as knowledge is concerned. > > Good tests, which really do test understanding > mimic the real world which is full of tests: > "Here's a deadline, if you don't meet it you're > fired and if you do meet it and it doesn't work > then you're still fired." Students in schools would *love* to be fired from the school. Many of them, anyway. The trouble is, if you fail the test, you aren't fired, you're just scolded, if that. I think it should be like this: kids should be taught basic reading and how to use calculator. Then they're told: come back when you want to learn more. > > That survival ethic has to be taught to kids somehow > and tests are a relatively gentle way of doing it. They are gentle, but they're not teaching survival. You survive just as well if you cheated or failed, you come to the same school, you don't get any pay cut, etc. If tests have a lesson, it is that failing at your task isn't much different from succeeding. > After all the important part of any education > system is not the imparting of knowledge but the > training in new behavioural patterns - the habits > of effective study, the ability to crystalize and > communicate ideas, the efficient and focused achievement > of goals etc. Of any education system but this world's. > > Just my 2 cents, > > alan g. > > PS Shouldn't this discussion be on the edu-sig > mailing list rather than tutor? :-) Yep.. if you want to reply to me, please do via e-mail! -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From glingl@aon.at Fri Oct 19 21:39:02 2001 From: glingl@aon.at (Gregor Lingl) Date: Fri, 19 Oct 2001 22:39:02 +0200 Subject: [Tutor] What is in future? Message-ID: <001701c158de$16814880$1664a8c0@mega> This is a multi-part message in MIME format. ------=_NextPart_000_0014_01C158EE.D9E70020 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi! Can anyone explain the following: Python 2.2b1 (#25, Oct 19 2001, 11:44:52) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> from __future__ import true_division SyntaxError: future feature true_division is not defined (, = line 1) >>>=20 Thanks Gregor Lingl ------=_NextPart_000_0014_01C158EE.D9E70020 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi!
Can anyone explain the=20 following:
 
Python 2.2b1 (#25, Oct 19 2001, = 11:44:52)=20 [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or = "license" for=20 more information.
IDLE 0.8 -- press F1 for help
>>> from=20 __future__ import true_division
SyntaxError: future feature = true_division is=20 not defined (<pyshell#0>, line 1)
>>>
 
Thanks
Gregor = Lingl
------=_NextPart_000_0014_01C158EE.D9E70020-- From Roger G. Lewis" Any reference to tutorial/examples on creation and use of *Arrays* in Python would be appreciated by this newbie. Have used them in BASIC so concepts are understood but details are not. Thanks. R. Lewis Ottawa, ON. Canada From lkvam@venix.com Fri Oct 19 23:15:33 2001 From: lkvam@venix.com (Lloyd Kvam) Date: Fri, 19 Oct 2001 18:15:33 -0400 Subject: [Tutor] Help on Arrays? References: <000501c158e9$dbe189e0$b038bfce@lewisr> Message-ID: <3BD0A605.31356600@venix.com> The nearest equivalent in Python are lists. a = [ 'one','two','three' ] is a three item list. The items can be accessed using array style indexing. a[0] = 'one'. Lists are zero based like your VB arrays. Square brackets [] are used for indexing in Python, not parentheses () as in VB. Lists are MUCH more flexible. You now know what you are looking for in going through the tutorials, etc. "Roger G. Lewis" wrote: > > Any reference to tutorial/examples on creation and use of *Arrays* in Python > would be appreciated by this newbie. Have used them in BASIC so concepts are > understood but details are not. Thanks. > > R. Lewis > Ottawa, ON. Canada > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From ak@silmarill.org Fri Oct 19 23:13:49 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Fri, 19 Oct 2001 18:13:49 -0400 Subject: [Tutor] Help on Arrays? In-Reply-To: <000501c158e9$dbe189e0$b038bfce@lewisr> References: <000501c158e9$dbe189e0$b038bfce@lewisr> Message-ID: <20011019181349.A18771@sill.silmarill.org> On Fri, Oct 19, 2001 at 06:03:14PM -0400, Roger G. Lewis wrote: > Any reference to tutorial/examples on creation and use of *Arrays* in Python > would be appreciated by this newbie. Have used them in BASIC so concepts are > understood but details are not. Thanks. > > R. Lewis > Ottawa, ON. Canada Sure, did you look at the python.org tutorial? The site also has links to other tutorials. Here's a short "crash course": >>> a = ["dog"] >>> a.append(2) >>> a ['dog', 2] >>> a = a + ["cat", 34] >>> a ['dog', 2, 'cat', 34] >>> a[0] 'dog' >>> a[2] 'cat' >>> for item in a: ... print item ... dog 2 cat 34 > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From dyoo@hkn.eecs.berkeley.edu Fri Oct 19 23:27:56 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 19 Oct 2001 15:27:56 -0700 (PDT) Subject: [Tutor] Help on Arrays? In-Reply-To: <000501c158e9$dbe189e0$b038bfce@lewisr> Message-ID: On Fri, 19 Oct 2001, Roger G. Lewis wrote: > Any reference to tutorial/examples on creation and use of *Arrays* in > Python would be appreciated by this newbie. Have used them in BASIC so > concepts are understood but details are not. Thanks. Alan Gauld's "Learn to Program Using Python" has a nice chapter on array-like sequences, so you might want to take a look at his web site: http://www.freenetpages.co.uk/hp/alan.gauld/ The stuff about arrays and lists starts off at "The Raw Materials": http://www.freenetpages.co.uk/hp/alan.gauld/tutdata.htm around the section labeled "Python Collections". There's a nice collection of tutorials off the Python.org website here: http://python.org/doc/Newbies.html and almost all of the tutorials there give a chapter or two on the Array/List idea. Arrays in computer languages are containers of a fixed size, dedicated to hold other values. Python has something that's similar to an array called a "List". Python lists are similar to arrays, although they have some differences. Let's see how to make a Python list: ### >>> mylist = [] >>> mylist [] ### And that's how to make an empty list. Of course, empty lists are... well... empty. It would be nice to start inserting values into our list. What makes Python lists nice is that they don't have a fixed size: they will grow as we append() new elements to them: ### >>> mylist.append(1) >>> mylist.append('once and future king') >>> mylist [1, 'once and future king'] ### To get at any element in a list, we can just point at it by using an "index" notation: ### >>> mylist[0] 1 >>> mylist[1] 'once and future king' >>> mylist[2] Traceback (most recent call last): File "", line 1, in ? IndexError: list index out of range ### So, in Python, the brackets '[' and ']' are associated with list-like things. The blockiness, I guess, is supposed to bring up an image or analogy of a boxy container. Take a look at the tutorials above: they are very good, and they will better introduce the subject of Lists to you. Feel free to ask questions here too. Good luck to you! From dyoo@hkn.eecs.berkeley.edu Fri Oct 19 23:32:11 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 19 Oct 2001 15:32:11 -0700 (PDT) Subject: [Tutor] What is in future? In-Reply-To: <001701c158de$16814880$1664a8c0@mega> Message-ID: On Fri, 19 Oct 2001, Gregor Lingl wrote: > Hi! > Can anyone explain the following: > > Python 2.2b1 (#25, Oct 19 2001, 11:44:52) [MSC 32 bit (Intel)] on win32 > Type "copyright", "credits" or "license" for more information. > IDLE 0.8 -- press F1 for help > >>> from __future__ import true_division > SyntaxError: future feature true_division is not defined (, line 1) According to: http://python.sourceforge.net/peps/pep-0238.html the syntax to bring over true division from the future is: ### from __future__ import division ### However, I don't have Python 2.2 installed yet, I can't confirm that this works. Try it out, and tell us if this works for you. Also, true division is something new for Python 2.2 --- it won't work for anything below Python 2.2, so be careful about not using this for code that's supposed to be compatible with older systems. Good luck! From urnerk@qwest.net Sat Oct 20 00:28:54 2001 From: urnerk@qwest.net (Kirby Urner) Date: Fri, 19 Oct 2001 16:28:54 -0700 Subject: [Tutor] Help on Arrays? In-Reply-To: <000501c158e9$dbe189e0$b038bfce@lewisr> Message-ID: <4.2.0.58.20011019161806.00a8b3b0@pop3.norton.antivirus> At 06:03 PM 10/19/2001 -0400, Roger G. Lewis wrote: >Any reference to tutorial/examples on creation and use of *Arrays* in Python >would be appreciated by this newbie. Have used them in BASIC so concepts are >understood but details are not. Thanks. > >R. Lewis >Ottawa, ON. Canada Note also that in addition to lists, which are arrays allowing any mix of objects, you have an 'array' module which lets your create arrays all of the same kind of thing. >>> from array import array >>> a = array('i',[1,2,3]) >>> a array('i', [1, 2, 3]) >>> a[0] 1 >>> type(a) They behave pretty much the same as lists, only faster. If you have a huge size of array, and the members are all integers, characters, floats or whatever, consider the array type. Also, if you augment Python with Numeric Python, an optional package for handling large arrays efficiently, you'll find yet another implementation of the array concept. In ordinary Python, using builtin features only, note that you have two kinds of "arrays": lists and tuples. The main difference is that tuples aren't designed to be appended to or to have their members changed -- they're what we call 'immutable'. That can be useful, if you're trying to prevent data from being overwritten by mistake. Many functions return tuples, vs. single values or even lists. From example, as part of the Standard Library you have the 'time' module: >>> import time >>> time.localtime() (2001, 10, 19, 16, 23, 25, 4, 292, 1) You can guess from the entries what these data give you. Note: if you want to format this tuple, the time module has options for this e.g.: >>> time.strftime("%a, %d %b %Y",time.localtime()) (the 2nd argument is optional if all you want is indeed the local time). Kirby From dsh8290@rit.edu Sat Oct 20 03:16:55 2001 From: dsh8290@rit.edu (dman) Date: Fri, 19 Oct 2001 22:16:55 -0400 Subject: [sill: Re: [Tutor] help ;-)] In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C006@mbtlipnt02.btlabs.bt.co.uk>; from alan.gauld@bt.com on Fri, Oct 19, 2001 at 12:44:05PM +0100 References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C006@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20011019221655.D17177@harmony.cs.rit.edu> On Fri, Oct 19, 2001 at 12:44:05PM +0100, alan.gauld@bt.com wrote: | > I agree with most of your post. | | Me too, but less than you maybe :-) | | > ... tests are a big mistake. It | > does encourage the students to try to "get by" | > with as little as possible. | | I'm not sure I agree that tets per se are bad. As I am currently a college student, I have the opinion that many tests are bad. Some tests don't really pertain to the course content or they ask questions that weren't really covered in class or labs or assignments. (For example, a recent test in Distributed Systems asking several detailed questions about COM even though COM was only presented as an overview) There are also many times that a test poorly reflects the knowledge or abilities of the student being tested. I have a friend who is in several of my classes. He works hard and knows at least the majority of the material. He can develop good code as well as the designs and architecture. His boss and coworkers at his recent co-op job (where he still works part time) really like his work too. I like having him in group projects. However, many times on tests he doesn't get very good marks. The tests don't accurately reflect his knowledge and capabilities, IMO. | What I don't like is the current trend to | multi-choice tests which can be passed in theory | by pure luck! Especially when out of 5 choices | there will usually be at least 1 that's obviously | dumb, another that's dumb with even basic | understanding - which leaves a 30% chance of | getting it right. Not much of a test. My favorite kind :-). Do you know how many people fail (or at least do poorly) on mc tests? (Some people call them "multiple guess") | Good tests, which really do test understanding | mimic the real world which is full of tests: | "Here's a deadline, if you don't meet it you're | fired and if you do meet it and it doesn't work | then you're still fired." I like the no-tests no-grades perspective. Instead the educator(s) should be able to testify on the student's behalf to those who want to know whether or not the student is capable of a given task. The more people a person works with/for the more people who know what the person is capable of. References are better than numbers, I think. If I work with someone, I see what the person is capable of. I don't care what grades they got, I know what they can do. Too bad the world isn't honest enough to operate like this. | That survival ethic has to be taught to kids somehow Don't you mean work ethic? Survival can be achieved by being injured while performing a crime, then suing for the incapacity to continue with your "livelihood". (ridiculous, I know) This world is horrible, but we knew that already, (didn't you?). The Bible explains it all :-). -D PS. sometimes the "off topic" threads are the most interesting From rufmetal@home.com Sat Oct 20 05:27:58 2001 From: rufmetal@home.com (Chris Keelan) Date: Fri, 19 Oct 2001 23:27:58 -0500 Subject: [sill: Re: [Tutor] help ;-)] In-Reply-To: <20011019221655.D17177@harmony.cs.rit.edu> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C006@mbtlipnt02.btlabs.bt.co.uk> <20011019221655.D17177@harmony.cs.rit.edu> Message-ID: <01101923275800.04781@tygesen> On Fri, 19 Oct 2001, dman wrote: [snip] > I like the no-tests no-grades perspective. Instead the educator(s) > should be able to testify on the student's behalf to those who want to > know whether or not the student is capable of a given task. The more > people a person works with/for the more people who know what the > person is capable of. References are better than numbers, I think. Only playing Devil's Advocate here, but how does the above merit system work with class sizes of 100+ students? When I was in university (admittedly not in CS) many of the profs never knew our names, much less were able to comment on our grasp of course content. > If I work with someone, I see what the person is capable of. I don't > care what grades they got, I know what they can do. Too bad the world > isn't honest enough to operate like this. I don't think that honesty is necessarily the issue. Just sticking my nose where it doesn't belong, as usual. - Chris From 55551212@email.com Sat Oct 20 07:31:45 2001 From: 55551212@email.com (55551212@email.com) Date: Fri, 19 Oct 2001 23:31:45 -0700 Subject: [Tutor] Advertisement: Get in on this NOW... Message-ID: Dear Future Millionaire: I'll make you a promise. READ THIS E-MAIL TO THE END! - follow what it says to the letter - and you will not worry whether a RECESSION is coming or not, who is President, or whether you keep your current job or not. Yes, I know what you are thinking. I never responded to one of these before either. One day though, something just said "you throw away $25.00 going to a movie for 2 hours with your wife". "What the heck." Believe me, no matter where you believe "those feelings" come from, I thank goodness every day that I had that feeling. I cannot imagine where I would be or what I would be doing had I not. Read on. It's true. Every word of it. It is legal. I checked. Simply because you are buying and selling something of value. AS SEEN ON NATIONAL TV: Making over half million dollars every 4 to 5 months from your home. THANK'S TO THE COMPUTER AGE AND THE INTERNET ! ================================================== BE AN INTERNET MILLIONAIRE LIKE OTHERS WITHIN A YEAR!!! Before you say ''Bull'', please read the following. This is the letter you have been hearing about on the news lately. Due to the popularity of this letter on the Internet, a national weekly news program recently devoted anentire show to the investigation of this program described below, to see if it really can make people money. The show also investigated whether or not the program was legal. Their findings proved once and for all that there are ''absolutely NO Laws prohibiting the participation in the program and if people can "follow the simple instruction" they are bound to make some mega bucks with only $25 out of pocket cost''. DUE TO THE RECENT INCREASE OF POPULARITY & RESPECT THIS PROGRAM HAS ATTAINED, IT IS CURRENTLY WORKING BETTER THAN EVER. This is what one had to say: '' Thanks to this profitable opportunity". I was approached many times before but each time I passed on it. I am so glad I finally joined just to see what one could expect in return for the minimal effort and money required. To my astonishment, I received a total $ 610,470.00 in 21 weeks, with money still coming in''. Pam Hedland, Fort Lee, New Jersey. ================================================== Another said: "this program has been around for a long time but I never believed in it. But one day when I received this again in the mail I decided to gamble my $25 on it. I followed the simple instructions and walaa ..... 3 weeks later the money started to come in. First month I only made $240.00 but the next 2 months after that I made a total of $290,000.00. So far, in the past 8 months by re-entering the program, I have made over $710,000.00 and I am playing it again. The key to success in this program is to follow the simple steps and NOT change anything.'' More testimonials later but first, ======= ==== PRINT THIS NOW FOR YOUR FUTURE REFERENCE ==== $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ If you would like to make at least $500,000 every 4 to 5 months easily and comfortably, please read the following...THEN READ IT AGAIN and AGAIN !!! $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ FOLLOW THE SIMPLE INSTRUCTION BELOW AND YOUR FINANCIAL DREAMS WILL COME TRUE, GUARANTEED! INSTRUCTIONS: =====Order all 5 reports shown on the list below ===== For each report, send $5 CASH, THE NAME & NUMBER OF THE REPORT YOU ARE ORDERING and YOUR E-MAIL ADDRESS to the person whose name appears ON THAT LIST next to the report. MAKE SURE YOUR RETURN ADDRESS IS ON YOUR ENVELOPE TOP LEFT CORNER in case of any mail problems. ===WHEN YOU PLACE YOUR ORDER, MAKE SURE === ===YOU ORDER EACH OF THE 5 REPORTS! === You will need all 5 reports so that you can save them on your computer and resell them. YOUR TOTAL COST $5 X 5 = $25.00. Within a few days you will receive, via e-mail, each of the 5 reports from these 5 different individuals. Save them on your computer so they will be accessible for you to send to the 1,000's of people who will order them from you. Also make a floppy of these reports and keep it on your desk in case something happens to your computer. IMPORTANT - DO NOT alter the names of the people who are listed next to each report, or their sequence on the list, in any way other than what is instructed below in step '' 1 through 6 '' or you will loose out on the majority of your profits. Once you understand the way this works, you will also see how it does not work if you change it. Remember, this method has been tested, and if you alter it, it will NOT work !!! People have tried to put their friends/relatives names on all five thinking they could get all the money. But it does not work this way. Believe us, some have tried to be greedy and then nothing happened. So Do Not try to change anything other than what is instructed. Because if you do, it will not work for you. Remember, honesty reaps the reward!!! This IS a legitimate BUSINESS. You are offering a product for sale and getting paid for it. Treat it as such and you will be VERY profitable in a short period of time. 1.. After you have ordered all 5 reports, take this advertisement and REMOVE the name & address of the person in REPORT # 5. This person has made it through the cycle and is no doubt counting their fortune. 2..Move the name & address in REPORT # 4 down TO REPORT # 5. 3.. Move the name & address in REPORT # 3 down TO REPORT # 4. 4.. Move the name & address in REPORT # 2 down TO REPORT # 3. 5.. Move the name & address in REPORT # 1 down TO REPORT # 2 6.... Insert YOUR name & address in the REPORT # 1 Position. PLEASE MAKE SURE you copy every name & address ACCURATELY! This is critical to YOUR success. ================================================== **** Take this entire letter, with the modified list of names, and save it on your computer. DO NOT MAKE ANY OTHER CHANGES. Save this on a disk as well just in case if you loose any data. To assist you with marketing your business on the internet, the 5 reports you purchase will provide you with invaluable marketing information which includes how to send bulk e-mails legally, where to find thousands of free classified ads and much more. There are 2 Primary methods to get this venture going: METHOD # 1: BY SENDING BULK E-MAIL LEGALLY ================================================== Let's say that you decide to start small, just to see how it goes, and we will assume You and those involved send out only 5,000 e-mails each. Let's also assume that the mailing receive only a 0.2% (2/10 of 1%) response (the response could be much better but lets just say it is only 0.2%). Also many people will send out hundreds of thousands e-mails instead of only 5,000 each). Continuing with this example, you send out only 5,000 e-mails. With a 0.2% response, that is only 10 orders for report # 1. Those 10 people responded by sending out 5,000 e-mail each for a total of 50,000. Out of those 50,000 e-mails only 0.2% responded with orders. That's=100 people responded and ordered Report # 2. Those 100 people mail out 5,000 e-mails each for a total of 500,000 e-mails. The 0.2% response to that is 1000 orders for Report # 3. Those 1000 people send 5,000 e-mail each for a total of 5 million e-mail sent out. The 0.2% response is 10,000 orders for Report # 4. Those 10,000 people send out 5,000 e-mails each for a total of 50,000,000 (50 million) e-mails. The 0.2% response to that is 100,000 orders for Report # 5. THAT'S 100,000 ORDERS TIMES $5 EACH = $500,000.00 (half a million dollars). Your total income in this example is: 1..... $50 + 2..... $500 + 3..... $5,000 + 4..... $50,000 + 5.... $500,000 .... Grand Total=$555,550.00 NUMBERS DO NOT LIE. GET A PENCIL & PAPER AND FIGURE OUT THE WORST POSSIBLE RESPONSES AND NO MATTER HOW YOU CALCULATE IT, YOU WILL STILL MAKE A LOT OF MONEY! ================================================== REMEMBER FRIEND, THIS IS ASSUMING ONLY 10 PEOPLE ORDERING OUT OF 5,000 YOU MAILED TO. Dare to think for a moment what would happen if everyone or half or even one 4th of those people mailed 100,000 e-mails each or more? There are over 150 million people on the Internet worldwide and counting, with thousands more coming on line every day. Believe me, many people will do just that, and more! METHOD # 2: BY PLACING FREE ADS ON THE INTERNET ================================================== Advertising on the net is very, very inexpensive and there are hundreds of FREE places to advertise. Placing a lot of free ads on the Internet will easily get a larger response. We strongly suggest you start with Method # 1 and add METHOD #2 as you go along. For every $5 you receive, all you must do is e-mail them the Report they ordered. That's it. Always provide same day service on all orders. This will guarantee that the e-mail they send out, with your name and address on it, will be prompt because they can not advertise until they receive the report. ===========AVAILABLE REPORTS ==================== The reason for the "cash" is not because this is illegal or somehow "wrong". It is simply about time. Time for checks or credit cards to be cleared or approved, etc. Concealing it is simply so no one can SEE there is money in the envelope and steal it before it gets to you. ORDER EACH REPORT BY ITS NUMBER & NAME ONLY. Notes: Always send $5 cash (U.S. CURRENCY) for each Report. Checks NOT accepted. Make sure the cash is concealed by wrapping it in at least 2 sheets of paper. On one of those sheets of paper, Write the NUMBER & the NAME of the Report you are ordering, YOUR E-MAIL ADDRESS and your name and postal address. PLACE YOUR ORDER FOR THESE REPORTS NOW : ================================================== REPORT# 1: 'The Insider's Guide To Advertising for Free On The Net Order Report #1 from Keith Gilbert 2822 N. Ridgewood St. Santa Ana, CA 92705 USA ________________________________________________________ REPORT # 2: The Insider's Guide To Sending Bulk Email On The Net Order Report # 2 from: Steve Stwan P.O. Box 23923 Federal Way, WA 98093 USA _________________________________________________________________ REPORT # 3: Secret To Multilevel Marketing On The Net Order Report # 3 from : Craig Wuthrich 2390 Falls Ave. E. Twin Falls, ID 83301 USA ______________________________________________________ REPORT # 4: How To Become A Millionaire Using MLM & The Net Order Report # 4 from: S. Wong 50 Burnhamthorpe Rd. West #401 Mississauga, Ontario, L5B 3C2 Canada _______________________________________________________ REPORT #5: How To Send Out One Million Emails For Free Order Report # 5 From: Zach Simmons 2135 Springwood Carrollton, TX 75006 USA _____________________________________________________ $$$$$$$$$ YOUR SUCCESS GUIDELINES $$$$$$$$$$$ Follow these guidelines to guarantee your success: === If you do not receive at least 10 orders for Report #1 within 2 weeks, continue sending e-mails until you do. === After you have received 10 orders, 2 to 3 weeks after that you should receive 100 orders or more for REPORT # 2. If you did not, continue advertising or sending e-mails until you do. **Once you have received 100 or more orders for Report # 2, YOU CAN RELAX, because the system is already working for you, and the cash will continue to roll in ! THIS IS IMPORTANT TO REMEMBER: Every time your name is moved down on the list, you are placed in front of a Different report. You can KEEP TRACK of your PROGRESS by watching which report people are ordering from you. IF YOU WANT TO GENERATE MORE INCOME SEND ANOTHER BATCH OF E-MAILS AND START THE WHOLE PROCESS AGAIN. There is NO LIMIT to the income you can generate from this business !!! ================================================= FOLLOWING IS A NOTE FROM THE ORIGINATOR OF THIS PROGRAM: You have just received information that can give you financial freedom for the rest of your life, with NO RISK and JUST A LITTLE BIT OF EFFORT. You can make more money in the next few weeks and months than you have ever imagined. Follow the program EXACTLY AS INSTRUCTED. Do Not change it in any way. It works exceedingly well as it is now. Remember to e-mail a copy of this exciting report after you have put your name and address in Report #1 and moved others to #2 .....# 5 as instructed above. One of the people you send this to may send out 100,000 ormore e-mails and your name will be on every one of them. Remember though, the more you send out the more potential customers you will reach. So my friend, I have given you the ideas, information, materials and opportunity to become financially independent. IT IS UP TO YOU NOW ! =============MORE TESTIMONIALS=============== '' My name is Mitchell. My wife, Jody and I live in Chicago. I am an accountant with a major U.S. Corporation and I make pretty good money. When I received this program I grumbled to Jody about receiving ''junk mail''. I made fun of the whole thing, spouting my knowledge of the population and percentages involved. I ''knew'' it wouldn't work. Jody totally ignored my supposed intelligence and few days later she jumped in with both feet. I made merciless fun of her, and was ready to lay the old ''I told you so'' on her when the thing didn't work. Well, the laugh was on me! Within 3 weeks she had received 50 responses. Within the next 45 days she had received total $ 147,200.00 ......... all cash! I was shocked. I have joined Jodyin her ''hobby''. Mitchell Wolf M.D., Chicago, Illinois ================================================ '' Not being the gambling type, it took me several weeks to make up my mind to participate in this plan. But conservative as I am, I decided that the initial investment was so little that there was just no way that I wouldn't get enough orders to at least get my money back''. '' I was surprised when I found my medium size post office box crammed with orders. I made $319,210.00 in the first 12 weeks. The nice thing about this deal is that it does not matter where people live. There simply isn't a better investment with a faster return and so big''. Dan Sondstrom, Alberta, Canada ================================================= '' I had received this program before. I deleted it, but later I wondered if I should have given it a try. Of course, I had no idea who to contact to get another copy, so I had to wait until I was e-mailed again by someone else.........11 months passed then it luckily came again...... I did not delete this one! I made more than $490,000 on my first try and all the money came within 22 weeks''. Susan De Suza, New York, N.Y. ================================================= '' It really is a great opportunity to make relatively easy money with little cost to you. I followed the simple instructions carefully and within 10 days the money started to come in. My first month I made $ 20, 560.00 and by the end of third month my total cash count was $ 362,840.00. Life is beautiful, Thanx to internet''. Fred Dellaca, Westport, New Zealand ================================================= ORDER YOUR REPORTS TODAY AND GET STARTED ON YOUR ROAD TO FINANCIAL FREEDOM ! ================================================= If you have any questions of the legality of this program, contact the Office of Associate Director for Marketing Practices, Federal Trade Commission, Bureau of Consumer Protection, Washington, D.C. ================================================= ONE TIME MAILING, NO NEED TO REMOVE ================================================= This message is sent in compliance of the proposed bill SECTION 301, paragraph (a)(2)(C) of S. 1618. Further transmission to you by the sender of this email may be stopped at no cost to you by sending a reply to: coho2@ziplip.com with the word REMOVE in the subject line. This message is not intended for residents in the State of Washington, screening of addresses has been done to the best of our technical ability. From tcervone@excellmfg.com Sat Oct 20 12:26:57 2001 From: tcervone@excellmfg.com (Tony Cervone) Date: Sat, 20 Oct 2001 07:26:57 -0400 Subject: [Tutor] one more question on a word in a specific place in a line Message-ID: <46553DB71DFED411992300A0C9E93832012E42@NTEXCELL> Thanks you very much, gentlemen. This is the greatest bunch of folks for someone who wants to learn Python. I am making very good progress on my problem. So here's a continuation of it: I am currently reading a text file that is essentially a weather report. It looks as follows: 12-23-01 KPVD yyyyyy/ggggg/kkkkkkk/lllllllllll 12-23-01 KLGAyyyyyy/ggggggg/kkkkkkkk I am using the readlines() and the line.split commands to print the "first word" in the second line, and the "first word" in the 4 line. My code works well if the text always looks like the above example. Sometimes, however, a different weather text may have some additional text that spills into the next line. For example 12-23-01 KPVD yyyyyy/ggggg/kkkkkkk/lllllllllll ZZZZ 12-23-01 KLGAyyyyyy/ggggggg/kkkkkkkk If this happens, the "first" word in the 4 line clearly will not be the same. My code will read and print 12-23-01 instead of KLGA. How do I do it so that in both cases the print out will be KPVD KLGA , and not KPVD 12-23-01 From toodles@yifan.net Sat Oct 20 14:19:38 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Sat, 20 Oct 2001 21:19:38 +0800 Subject: [Tutor] one more question on a word in a specific place in a line References: <46553DB71DFED411992300A0C9E93832012E42@NTEXCELL> Message-ID: <001401c15969$e0136490$0300a8c0@sun> > Thanks you very much, gentlemen. I think that really should be ladies and gentlemen :) > I am using the readlines() and the line.split commands to print the "first > word" in the second line, and the "first word" in the 4 line. My code works > well if the text always looks like the above example. Sometimes, however, a > different weather text may have some additional text that spills into the > next line. For example > 12-23-01 > KPVD yyyyyy/ggggg/kkkkkkk/lllllllllll > ZZZZ > > 12-23-01 > KLGAyyyyyy/ggggggg/kkkkkkkk I've just put this into a file called weather.dat for reference to my code. (Should there be a space between KLGA and y? I took the liberty of adding a space in weather.dat...) One way of doing this is separating each record into items in a list. You could separate around the blank lines like so: --- data=open("weather.dat").readlines() records=[] while data: if '\n' in data: #if there is a totally blank line, separate the data around it records.append(data[:data.index('\n')]) del data[:data.index('\n')+1] else: records.append(data) data=None for record in records: print record[1].split(' ')[0] #print the first 4 characters from 2nd line of each record --- > > If this happens, the "first" word in the 4 line clearly will not be the > same. My code will read and print 12-23-01 instead of KLGA. > How do I do it so that in both cases the print out will be KPVD KLGA , and > not KPVD 12-23-01 Regards, Andrew > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From sburr@mac.com Sat Oct 20 18:36:30 2001 From: sburr@mac.com (Steven Burr) Date: Sat, 20 Oct 2001 10:36:30 -0700 Subject: [Tutor] What is in future? In-Reply-To: Message-ID: On Friday, October 19, 2001, at 03:32 PM, Danny Yoo wrote: > On Fri, 19 Oct 2001, Gregor Lingl wrote: > >> Hi! >> Can anyone explain the following: >> >> Python 2.2b1 (#25, Oct 19 2001, 11:44:52) [MSC 32 bit (Intel)] on win32 >> Type "copyright", "credits" or "license" for more information. >> IDLE 0.8 -- press F1 for help >>>>> from __future__ import true_division >> SyntaxError: future feature true_division is not defined (, >> line 1) > > According to: > > http://python.sourceforge.net/peps/pep-0238.html > > the syntax to bring over true division from the future is: > > ### > from __future__ import division > ### > > However, I don't have Python 2.2 installed yet, I can't confirm that > this > works. Try it out, and tell us if this works for you. $ python Python 2.2a4 (#1, Oct 3 2001, 21:37:06) [GCC 2.95.2 19991024 (release)] on darwin1 Type "help", "copyright", "credits" or "license" for more information. >>> from __future__ import division >>> 2/3 0.66666666666666663 There it is, floating point math in all its glory. : ) From severinofer@recol.es Sat Oct 20 18:47:36 2001 From: severinofer@recol.es (Severino Fernandez) Date: Sat, 20 Oct 2001 19:47:36 +0200 Subject: [Tutor] compile.py for Windows availability ? Message-ID: Does someone know where I can find the compile.py file for Windows ? Severino Fernandez Instituto Nacional de Tecnica Aeroespacial Departamento de Observación de la Tierra, Teledetección y Aeronomía Carretera de Ajalvir, Km 4 28850 Torrejon de Ardoz Spain Tel +34 91 677 41 30 +34 91 677 41 90 +34 91 305 16 52 Fax +34 91 677 46 46 Email severinofer@recol.es From glingl@aon.at Sat Oct 20 19:09:18 2001 From: glingl@aon.at (Gregor Lingl) Date: Sat, 20 Oct 2001 20:09:18 +0200 Subject: [Tutor] What is in future? Message-ID: <00cb01c15992$562be8a0$1664a8c0@mega> ----- Original Message ----- From: "Danny Yoo" To: "Gregor Lingl" > the syntax to bring over true division from the future is: > > ### > from __future__ import division > ### > > However, I don't have Python 2.2 installed yet, I can't confirm that this > works. Try it out, and tell us if this works for you. > > Also, true division is something new for Python 2.2 --- it won't work for > anything below Python 2.2, so be careful about not using this for code > that's supposed to be compatible with older systems. > > Good luck! > > Yes, it works. Thanks! Gregor Just another question: Is it possible to start up IDLE in a way, that 'true division' is alreay enabled? (Is there some sort of startup-script, where I can put in the import statement?) From csmith@blakeschool.org Sat Oct 20 20:51:55 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Sat, 20 Oct 2001 14:51:55 -0500 Subject: [Tutor] Re: one more question on a word in a specific place in a line In-Reply-To: References: Message-ID: > >One way of doing this is separating each record into items in a list. You >could separate around the blank lines like so: A more general alternative is to access the file as a "record" file with something like the class that Bjorn Peterson previously discussed. Doing so allows you to read records separated by an arbitrary delimiter just like you would read lines from a file: file='mydatfile' delim='\n\n' f = rfile(file,delim) #instead of f=open(file,'r') while 1: rec = f.read_record() if rec==None: break lines=rec.split('\n') print lines[1][:3] #the first 4 characters on the 2nd line f.close() My modification of Bjorn's class along with a read_records() method is given below. /c # # Python class for reading a variable length record file # with fixed multi-character delimiter; a combination of # Bjorn Peterson's class and read_record and my read_records # # cps 9/17/01 # class rfile: def __init__(self, filename, delimiter, bufsize=100000): self.fhand = open(filename) self.bufsize = bufsize self.buffer = "" self.delim = delimiter self.dlen = len(delimiter) self.eof = 0 def read_record(self): # either return None and record w/o delim # OR '' and record with delim if self.eof: return None while self.buffer.find(self.delim)==-1: c=self.fhand.read(self.bufsize) if not c: self.eof = 1 return self.buffer self.buffer += c itsat=self.buffer.find(self.delim) record = self.buffer[:itsat] self.buffer = self.buffer[itsat+self.dlen:] return record def read_records(self): # # This is only necessary in case this is called after # already getting all the records. # if self.eof: return [] data = '' records = [] while 1: readData = self.fhand.read(self.bufsize) if not readData: break data += readData if data.find(self.delim)<>-1: partialRecords = data.split(self.delim) records += partialRecords[:-1] data = partialRecords[-1] if data: records += [data] self.eof = 1 return records def close(self): self.fhand.close() #main program test file='try' delim='\n\n' # read them all at once f = rfile(file, delim) recs=f.read_records() print recs f.close() # or read them one at a time f = rfile(file,delim) rno = 0 while 1: line = f.read_record() if line==None: break print "REC",rno print line rno = rno + 1 f.close() From dsh8290@rit.edu Sat Oct 20 21:09:40 2001 From: dsh8290@rit.edu (dman) Date: Sat, 20 Oct 2001 16:09:40 -0400 Subject: [sill: Re: [Tutor] help ;-)] In-Reply-To: <01101923275800.04781@tygesen>; from rufmetal@home.com on Fri, Oct 19, 2001 at 11:27:58PM -0500 References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C006@mbtlipnt02.btlabs.bt.co.uk> <20011019221655.D17177@harmony.cs.rit.edu> <01101923275800.04781@tygesen> Message-ID: <20011020160940.B24483@harmony.cs.rit.edu> On Fri, Oct 19, 2001 at 11:27:58PM -0500, Chris Keelan wrote: | On Fri, 19 Oct 2001, dman wrote: | | [snip] | | > I like the no-tests no-grades perspective. Instead the educator(s) | > should be able to testify on the student's behalf to those who want to | > know whether or not the student is capable of a given task. The more | > people a person works with/for the more people who know what the | > person is capable of. References are better than numbers, I think. | | Only playing Devil's Advocate here, but how does the above merit system work | with class sizes of 100+ students? When I was in university (admittedly not | in CS) many of the profs never knew our names, much less were able to comment | on our grasp of course content. This system doesn't really work in that context. I have had only one class (General Chemistry I) that was of that magnitude. I can't speak for other schools or majors, but most of my classes are fairly small (12-30 students) and many of them have a lab associated with the class that is smaller than the class (for example, 1 lecture section and 2 lab sections). Also, the higher level the course the fewer students there are. As a student progresses, it becomes more likely that the profs will get to know the student, especially if the student consistently does well. Also, the teacher/prof isn't the only person who can testify as to the student's capabilities. Any person can. Obviously, then, it is up to the investigator (employer, whoever) to evaluate the weight the reference should hold. | > If I work with someone, I see what the person is capable of. I don't | > care what grades they got, I know what they can do. Too bad the world | > isn't honest enough to operate like this. | | I don't think that honesty is necessarily the issue. Suppose you fail miserably at some task or course or whatever. Then you and your friends get together and agree to lie and say that you are excellent at it. It can be an issue. | Just sticking my nose where it doesn't belong, as usual. You can do that in a public forum ;-)? Certainly my idea is rather idealistic and not likely to happen in practice. -D From dyoo@hkn.eecs.berkeley.edu Sat Oct 20 21:39:48 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 20 Oct 2001 13:39:48 -0700 (PDT) Subject: [Tutor] What is in future? In-Reply-To: <00cb01c15992$562be8a0$1664a8c0@mega> Message-ID: On Sat, 20 Oct 2001, Gregor Lingl wrote: > Just another question: > > Is it possible to start up IDLE in a way, that 'true division' is > alreay enabled? (Is there some sort of startup-script, where I can put > in the import statement?) If you add a file called sitecustomize.py in the Python library directory, Python should import that file for you, so you can add some customizations there. However, I'm not sure if "from __future__ import division" can be set up as a default using sitecustomize.py. If it behaves anything like the "nested_scope" directive, then the "division" directive is isolated to the file that contains the directive. That is, the "future" appears to only affect the file that it's inside. I could be completely wrong about this though. *grin* From urnerk@qwest.net Sat Oct 20 22:09:56 2001 From: urnerk@qwest.net (Kirby Urner) Date: Sat, 20 Oct 2001 14:09:56 -0700 Subject: [Tutor] What is in future? In-Reply-To: References: <00cb01c15992$562be8a0$1664a8c0@mega> Message-ID: <4.2.0.58.20011020140132.015bbbc0@pop3.norton.antivirus> > >However, I'm not sure if "from __future__ import division" >can be set up as a default using sitecustomize.py. Apparently this doesn't work. I gave it a try. Note that nested_scopes is the default in the latest 2.2 -- no need to import from __future__ to get that. Example: Python 2.2a4 (#24, Sep 27 2001, 21:44:09) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> def f(x): y = 4 g = lambda x: x+y return g(x) >>> f(3) 7 Kirby From discuss@sendme.cz Sat Oct 20 22:41:34 2001 From: discuss@sendme.cz (A) Date: Sat, 20 Oct 2001 23:41:34 +0200 Subject: [Tutor] Smtplib module Message-ID: <3BD20BAE.6346.7693E0@localhost> Hi, I want to use smtplib module for sending emails. Is there any way how I can test a return code, generated by this module, to see if an email was accepting for delivery, for example? Thank you for help. From discuss@sendme.cz Sat Oct 20 22:41:34 2001 From: discuss@sendme.cz (A) Date: Sat, 20 Oct 2001 23:41:34 +0200 Subject: [Tutor] Re:Python script engine - Thanks Message-ID: <3BD20BAE.9563.7693B3@localhost> I would like to thank you all that answered my question. Execfile() will do all that I need. Thanks. Ladislav From sheila@thinkspot.net Sat Oct 20 23:00:22 2001 From: sheila@thinkspot.net (Sheila King) Date: Sat, 20 Oct 2001 15:00:22 -0700 Subject: [Tutor] Smtplib module In-Reply-To: <3BD20BAE.6346.7693E0@localhost> References: <3BD20BAE.6346.7693E0@localhost> Message-ID: <64234E4A5D@kserver.org> On Sat, 20 Oct 2001 23:41:34 +0200, "A" wrote about [Tutor] Smtplib module: :Hi, :I want to use smtplib module for sending emails. :Is there any way how I can test a return code, generated by this :module, to see if an email was accepting for delivery, for example? :Thank you for help. Sure. import smtplib message = """\ To: me@mydomain.com From: me@mydomain.com Subject: testing smtp response Date: Sat, Oct 20 2001 15:00 -0700 Here is the message body. """ SENDER = 'me@mydomain' RECIPIENT = 'me@mydomain' server = smtplib.SMTP('localhost') response = server.sendmail(SENDER, RECIPIENT, message) server.close() print response # I think the above code is correct, but I didn't test-run it. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From sheila@thinkspot.net Sat Oct 20 23:06:38 2001 From: sheila@thinkspot.net (Sheila King) Date: Sat, 20 Oct 2001 15:06:38 -0700 Subject: [Tutor] Smtplib module In-Reply-To: <64234E4A5D@kserver.org> References: <3BD20BAE.6346.7693E0@localhost> <64234E4A5D@kserver.org> Message-ID: <69DB816C27@kserver.org> Doh! there is a mistake in the script that I noticed, right after I clicked on "send". Read on: On Sat, 20 Oct 2001 15:00:22 -0700, Sheila King wrote about Re: [Tutor] Smtplib module: :import smtplib : :message = """\ :To: me@mydomain.com :From: me@mydomain.com :Subject: testing smtp response :Date: Sat, Oct 20 2001 15:00 -0700 : :Here is the message body. :""" : :SENDER = 'me@mydomain' :RECIPIENT = 'me@mydomain' : :server = smtplib.SMTP('localhost') :response = server.sendmail(SENDER, RECIPIENT, message) :server.close() : :print response That last line above needs to be: print str(response) I believe if you check the docs for the smtplib module, you will find that the response that is returned is a (?) list or dictionary of the response for each SMTP envelope recipient. Since response isn't a string, you can't print it. However, you can convert the response to a string, or write special code to handle the dictionary/list (whichever it is), and parse the individual results. For my needs, which are not that complex at the moment, I just convert it to a string and write it to a log. HTH, -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From glingl@aon.at Sat Oct 20 23:31:42 2001 From: glingl@aon.at (Gregor Lingl) Date: Sun, 21 Oct 2001 00:31:42 +0200 Subject: [Tutor] a strange(r's) question Message-ID: <005301c159b6$fe3e24d0$1664a8c0@mega> This is a multi-part message in MIME format. ------=_NextPart_000_0050_01C159C7.C197A770 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable As my native language is German, I don't know how=20 Tkinter is pronounced correctly in English. Thanks for answering to this somewhat=20 off-programming question Gregor Lingl P.S. As I'm teaching Python, I have to=20 talk about it. ------=_NextPart_000_0050_01C159C7.C197A770 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
As my native language is = German, I=20 don't
know how
 
      =20 Tkinter
 
is pronounced correctly in=20 English.
 
Thanks for answering to this = somewhat=20
off-programming = question
 
Gregor Lingl
 
P.S. As I'm teaching Python, I = have to=20
talk about = it.
------=_NextPart_000_0050_01C159C7.C197A770-- From glingl@aon.at Sun Oct 21 00:53:59 2001 From: glingl@aon.at (Gregor Lingl) Date: Sun, 21 Oct 2001 01:53:59 +0200 Subject: [Tutor] Developing GUI-programs using IDLE Message-ID: <009601c159c2$80edcc40$1664a8c0@mega> This is a multi-part message in MIME format. ------=_NextPart_000_0093_01C159D3.40368190 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi folks! I'd like to develop GUI-programs with Tkinter using IDLE. (Remark: I'm running Python under WindowsNT) Apparently there arise problems from the fact, that IDLE itself is a Tkinter-program. Running the following program (taken from life-preserver): from Tkinter import * = = class Application(Frame): = def say_hi(self): = print "hi there, everyone!" = = def createWidgets(self): = self.QUIT =3D Button(self) = =20 self.QUIT["text"] =3D "QUIT" = =20 self.QUIT["fg"] =3D "red" = =20 self.QUIT["command"] =3D self.quit # crucial point = No. 1 =20 =20 self.QUIT.pack({"side": "left"}) =20 =20 self.hi_there =3D Button(self) = =20 self.hi_there["text"] =3D "Hello", = =20 self.hi_there["command"] =3D self.say_hi = =20 =20 self.hi_there.pack({"side": "left"}) =20 =20 =20 def __init__(self, master=3DNone): = =20 Frame.__init__(self, master) =20 self.pack() =20 self.createWidgets() =20 =20 app =3D Application() = =20 app.mainloop() # crucial point No. 2 =20 results in: a) if I press the QUIT-button IDLE collapses as a whole b) if I click on the window-closing 'x' (right upper corner) the programs window closes, but the REP-loop of IDLE does not return, so I have to kill it via the Task-Manager (I don't know how to kill the running program alone) if I delete (comment out) the last statement:=20 app.mainloop() a) remains the same b) (seemingly) works well: window closes,=20 new prompt in IDLE appears if I try to remedy point a) above by replacing self.quit by self.destroy (assuming self to be App that is Frame) something very strange occurs: pressing the QUIT-button results in disappearance of BOTH buttons, and the empty Frame-window remains on the screen. Now I also can remove the Frame by using 'x' I would appreciate very much a) an explanation of this weird behaviour b) a directive for how to handle mainloop() in the given circumstances c) a statement (method-call) that causes the Application to close and exit properly without killing IDLE Otherwise developing GUI-programs with IDLE would be rather uncomfortable. Gregor Lingl ------=_NextPart_000_0093_01C159D3.40368190 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi folks!
 
I'd like to develop = GUI-programs with=20 Tkinter
using IDLE. (Remark: I'm = running Python=20 under
WindowsNT)
 
Apparently there arise problems = from the=20 fact,
that IDLE itself is a=20 Tkinter-program.
 
 
Running the following = program (taken=20 from life-preserver):
 
from Tkinter import=20 *            =             &= nbsp;           &n= bsp;           &nb= sp;  =20
           &nb= sp;           &nbs= p;            = ;            =             &= nbsp;           =20
class=20 Application(Frame):         =             &= nbsp;           &n= bsp;           &nb= sp; =20
    def=20 say_hi(self):          =             &= nbsp;           &n= bsp;           &nb= sp;    =20
           &nb= sp;   =20 print "hi there,=20 everyone!"          &nb= sp;           &nbs= p;      =20
           &nb= sp;           &nbs= p;            = ;            =             &= nbsp;           =20
    def=20 createWidgets(self):         = ;            =             &= nbsp;          =20
           &nb= sp;   =20 self.QUIT =3D=20 Button(self)          &= nbsp;           &n= bsp;         =20
           &nb= sp;   =20 self.QUIT["text"] =3D=20 "QUIT"           &= nbsp;           &n= bsp;      =20
           &nb= sp;   =20 self.QUIT["fg"]   =3D=20 "red"           &n= bsp;           &nb= sp;      =20
           &nb= sp;   =20 self.QUIT["command"] =3D  self.quit   # crucial = point No.=20 1            =   
         &nb= sp;           &nbs= p;            = ;            =             &= nbsp;           &n= bsp; 
          = ;     =20 self.QUIT.pack({"side":=20 "left"})           = ;            = =20
           &nb= sp;           &nbs= p;            = ;            =             &= nbsp;          =20
           &nb= sp;   =20 self.hi_there =3D=20 Button(self)          &= nbsp;           &n= bsp;    =20
           &nb= sp;   =20 self.hi_there["text"] =3D=20 "Hello",           = ;            = =20
           &nb= sp;   =20 self.hi_there["command"] =3D=20 self.say_hi          &n= bsp;      =20
           &nb= sp;           &nbs= p;            = ;            =             &= nbsp;          =20
           &nb= sp;   =20 self.hi_there.pack({"side":=20 "left"})           = ;        =20
           &nb= sp;           &nbs= p;            = ;            =             &= nbsp;          =20
           &nb= sp;           &nbs= p;            = ;            =             &= nbsp;          =20
    def __init__(self,=20 master=3DNone):         &nbs= p;            = ;            =  =20
           &nb= sp;   =20 Frame.__init__(self,=20 master)           =             &= nbsp;   =20
           &nb= sp;   =20 self.pack()          &n= bsp;           &nb= sp;           &nbs= p; =20
           &nb= sp;   =20 self.createWidgets()         = ;            =             &= nbsp; =20
           &nb= sp;           &nbs= p;            = ;            =             &= nbsp;          =20
app =3D=20 Application()          =             &= nbsp;           &n= bsp;           &nb= sp;     =20
app.mainloop()   # crucial point=20 No. 2          &nb= sp;         =20
 
results in:
   a) if I press the = QUIT-button=20 IDLE collapses as a whole
   b) if I click on = the=20 window-closing 'x' (right upper corner)
      the=20 programs window closes, but the REP-loop of IDLE does
      = not return,=20 so I have to kill it via the Task-Manager
      (I=20 don't know how to kill the running program alone)
 
if I delete (comment = out) the last=20 statement:
app.mainloop()
   a) remains the=20 same
   b) (seemingly) = works well:=20 window closes,
      = new prompt=20 in IDLE appears
 
if I try to remedy point = a) above by=20 replacing self.quit
by self.destroy (assuming self = to be=20 App that is Frame)
something very strange occurs: = pressing the=20 QUIT-button results
in disappearance of BOTH = buttons, and the=20 empty Frame-window remains
on the screen. Now I also can = remove the=20 Frame by using 'x'
 
I would appreciate very = much
 a) an explanation of this = weird=20 behaviour
 b) a directive for how to = handle=20 mainloop() in the given
   =20 circumstances
 c) a statement = (method-call) that=20 causes the Application
    to close and = exit=20 properly without killing IDLE
 
Otherwise developing = GUI-programs with IDLE=20 would be rather
uncomfortable.
 
Gregor Lingl
 
------=_NextPart_000_0093_01C159D3.40368190-- From wheelege@tsn.cc Sun Oct 21 02:23:26 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Sun, 21 Oct 2001 11:23:26 +1000 Subject: [Tutor] Smtplib module References: <3BD20BAE.6346.7693E0@localhost> <64234E4A5D@kserver.org> <69DB816C27@kserver.org> Message-ID: <007d01c159ce$fc4e27c0$3ba616ca@ACE> um... > <..> > > :print response > > > That last line above needs to be: > > print str(response) > > I believe if you check the docs for the smtplib module, you will find > that the response that is returned is a (?) list or dictionary of the > response for each SMTP envelope recipient. Since response isn't a > string, you can't print it. However, you can convert the response to a > string, or write special code to handle the dictionary/list (whichever > it is), and parse the individual results. > I think you may be getting dictionary and list confused with perhaps an object which defines it's own str() function? Have a look at this interpreter session... >>> d = ['1', 2, 3] >>> print d ['1', 2, 3] >>> print str(d) ['1', 2, 3] >>> d = {1:2, 3:4} >>> print d {3: 4, 1: 2} >>> print str(d) {3: 4, 1: 2} >>> Just having a quick squiz at the doc's reveals "If this method does not throw an exception, it returns a dictionary, with one entry for each recipient that was refused.". So if it throws an exception, look in the docs to find otu more about it, if not then you will get a dict back for each one which was refused. Sorry to nitpick, Glen From dsh8290@rit.edu Sun Oct 21 02:36:10 2001 From: dsh8290@rit.edu (dman) Date: Sat, 20 Oct 2001 21:36:10 -0400 Subject: [Tutor] a strange(r's) question In-Reply-To: <005301c159b6$fe3e24d0$1664a8c0@mega>; from glingl@aon.at on Sun, Oct 21, 2001 at 12:31:42AM +0200 References: <005301c159b6$fe3e24d0$1664a8c0@mega> Message-ID: <20011020213609.B25563@harmony.cs.rit.edu> On Sun, Oct 21, 2001 at 12:31:42AM +0200, Gregor Lingl wrote: | As my native language is German, I don't | know how | | Tkinter | | is pronounced correctly in English. Well, my native language is English, but I don't know the correct way. I say (to myself anyways) T-K-inter. I've never had occaision to discuss it outside of mailing lists. | Thanks for answering to this somewhat | off-programming question No problem. | P.S. As I'm teaching Python, I have to | talk about it. Cool. Wish I could take courses in python instead of java. I am doing a project as a python-java hybrid. The project is to build a mail client (feature-bloated outlook-style). It is an exercise in architecture more than implementation. The coolest part is Moshe Zadka's PMS framework already takes care of the core of it :-). HTH, -D From wheelege@tsn.cc Sun Oct 21 02:34:01 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Sun, 21 Oct 2001 11:34:01 +1000 Subject: [Tutor] a strange(r's) question References: <005301c159b6$fe3e24d0$1664a8c0@mega> Message-ID: <00a201c159d0$76dc4020$3ba616ca@ACE> Heh, there have been plenty of um 'discussions' about this with me and friends, but to quote a guy who should know alot about it - 'Tkinter (pronounced tea-kay-inter), ...'. That's from John Grayson, the back cover of his book 'Python and Tkinter programming'. Although I must admit I do usually pronounce it t-kinter in my mind :) HTH, Glen ----- Original Message ----- From: "Gregor Lingl" To: Sent: Sunday, October 21, 2001 8:31 AM Subject: [Tutor] a strange(r's) question As my native language is German, I don't know how Tkinter is pronounced correctly in English. Thanks for answering to this somewhat off-programming question Gregor Lingl P.S. As I'm teaching Python, I have to talk about it. From sheila@thinkspot.net Sun Oct 21 02:47:15 2001 From: sheila@thinkspot.net (Sheila King) Date: Sat, 20 Oct 2001 18:47:15 -0700 Subject: [Tutor] Smtplib module In-Reply-To: <007d01c159ce$fc4e27c0$3ba616ca@ACE> References: <3BD20BAE.6346.7693E0@localhost> <64234E4A5D@kserver.org> <69DB816C27@kserver.org> <007d01c159ce$fc4e27c0$3ba616ca@ACE> Message-ID: <133F7C2438F@kserver.org> On Sun, 21 Oct 2001 11:23:26 +1000, "Glen Wheeler" wrote about Re: [Tutor] Smtplib module: :>>> d = ['1', 2, 3] :>>> print d :['1', 2, 3] :>>> print str(d) :['1', 2, 3] :>>> d = {1:2, 3:4} :>>> print d :{3: 4, 1: 2} :>>> print str(d) :{3: 4, 1: 2} :>>> OH! You know what...I don't actually use the "print" command in the code where I use this technique. I use a command like f.write(response) where f is an opened file object. So, in that case I DO have to convert response to a string. With print, of course, it doesn't matter. : Just having a quick squiz at the doc's reveals "If this method does not :throw an exception, it returns a dictionary, with one entry for each :recipient that was refused.". So if it throws an exception, look in the :docs to find otu more about it, if not then you will get a dict back for :each one which was refused. No, it returns a SINGLE dictionary with an entry for each recipient that was refused, not a dict for each one that was refused. Read the quote you just wrote. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From wheelege@tsn.cc Sun Oct 21 02:56:12 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Sun, 21 Oct 2001 11:56:12 +1000 Subject: [Tutor] Smtplib module References: <3BD20BAE.6346.7693E0@localhost> <64234E4A5D@kserver.org> <69DB816C27@kserver.org> <007d01c159ce$fc4e27c0$3ba616ca@ACE> <133F7C2438F@kserver.org> Message-ID: <00c001c159d3$91ad26a0$3ba616ca@ACE> > : Just having a quick squiz at the doc's reveals "If this method does not > :throw an exception, it returns a dictionary, with one entry for each > :recipient that was refused.". So if it throws an exception, look in the > :docs to find otu more about it, if not then you will get a dict back for > :each one which was refused. > > No, it returns a SINGLE dictionary with an entry for each recipient that > was refused, not a dict for each one that was refused. Read the quote > you just wrote. lol, I mean to write '...you will get a dict entry back for...'. No excuses for that one. :D From wheelege@tsn.cc Sun Oct 21 03:24:47 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Sun, 21 Oct 2001 12:24:47 +1000 Subject: [Tutor] Developing GUI-programs using IDLE References: <009601c159c2$80edcc40$1664a8c0@mega> Message-ID: <00ee01c159d7$aa71a5e0$3ba616ca@ACE> In the absence of any replies, I'll try my hand at helping you out. I doubt my ability though, so if something I say seems a little odd, then it's probably wrong. Here goes... > Apparently there arise problems from the fact, > that IDLE itself is a Tkinter-program. That's what most of the things your encountering are symptoms of. I found the best way to develop tkinter programs is to create a batch file (*.bat) which you then throw on your shortcut bit in the start bar or desktop, then double click on that to run a predetermined python script. That means running through a dos box is actually pretty quick. And most important of all, it works :) I was using the PythonWin environment from Activestate (get it from the downloads page at python.org) to develop tkinter programs, because it does not exhibit these problems. However, upon trying your example inside it there was different but no less irritating errors. I really don't know why this would be. > Running the following program (taken from life-preserver): > > <...> > > results in: > a) if I press the QUIT-button IDLE collapses as a whole Here is where I'm not sure. I think that when tkinter gets a call from quit it recursively searches and kills all mainloop()'s. I think. > b) if I click on the window-closing 'x' (right upper corner) > the programs window closes, but the REP-loop of IDLE does > not return, so I have to kill it via the Task-Manager > (I don't know how to kill the running program alone) I think (so confident!) this is because IDLE's mainloop gets confused with the program's mainloop and funny things happen. Somewhere I read that tcl/tk can only ever have one mainloop going inside any one program, and when you start up another inside the script then that takes over from IDLE's mainloop, so that when you stop it IDLE stops too. But I am probably wrong :) > if I delete (comment out) the last statement: > app.mainloop() > a) remains the same Again, I think that is deliberate. > b) (seemingly) works well: window closes, > new prompt in IDLE appears That is the recommended way to test tkinter programs through IDLE, and sorta works but really...I'd use the batch file. > if I try to remedy point a) above by replacing self.quit > by self.destroy (assuming self to be App that is Frame) > something very strange occurs: pressing the QUIT-button results > in disappearance of BOTH buttons, and the empty Frame-window remains > on the screen. Now I also can remove the Frame by using 'x' I've got no idea about this one. I had a look through the code and self.destroy should kill the frame....which it does do in the PythonWin environment, but leaves the two buttons and the window. One thing I noticed is that there is no root = Tk() call inside the script, mayhap that could have somethin to do with it? > I would appreciate very much > a) an explanation of this weird behaviour I tried :) > b) a directive for how to handle mainloop() in the given > circumstances I'd use the batch method, if you need help on that then just repost. > c) a statement (method-call) that causes the Application > to close and exit properly without killing IDLE Again...I don't know except for leaving out the mainloop() call, and even that has it's problems. I'd go for the batch deal. > Otherwise developing GUI-programs with IDLE would be rather > uncomfortable. It is :) HTH, Glen From urnerk@qwest.net Sun Oct 21 03:48:34 2001 From: urnerk@qwest.net (Kirby Urner) Date: Sat, 20 Oct 2001 19:48:34 -0700 Subject: [Tutor] Developing GUI-programs using IDLE In-Reply-To: <009601c159c2$80edcc40$1664a8c0@mega> Message-ID: <4.2.0.58.20011020194547.019d4330@pop3.norton.antivirus> > >Otherwise developing GUI-programs with IDLE would be rather >uncomfortable. > >Gregor Lingl I think you will find that developing GUI-programs (that use Tk) in IDLE *is* rather uncomfortable. That's a drawback of IDLE. I agree with the earlier poster: go ahead and edit/reload in IDLE, but test with another icon that bypasses IDLE. Kirby From glingl@aon.at Sun Oct 21 13:03:47 2001 From: glingl@aon.at (Gregor Lingl) Date: Sun, 21 Oct 2001 14:03:47 +0200 Subject: [Tutor] Re: Developing GUI-programs using IDLE Message-ID: <014001c15a28$70aa1170$1664a8c0@mega> ----- Original Message ----- From: "Kirby Urner" To: Sent: Sunday, October 21, 2001 4:48 AM Subject: Re: [Tutor] Developing GUI-programs using IDLE > > > >Otherwise developing GUI-programs with IDLE would be rather > >uncomfortable. > > > >Gregor Lingl > > I think you will find that developing GUI-programs > (that use Tk) in IDLE *is* rather uncomfortable. > That's a drawback of IDLE. > > I agree with the earlier poster: go ahead and > edit/reload in IDLE, but test with another icon > that bypasses IDLE. > > Kirby > What a pity! Nevertheless, thanks to both of you. I like to use it in interactive mode to show the working of Tkinter. It's quite nice to observe Tkinter-Objects react on single (e.g. config-) statements step by step, and it helps to learn Tkinter. I wonder, if it would be possible to enhance IDLE (which (version 0.8) still seems to be in an unmature state) by some sort of multi-threading mechanism, so GUI-apps could run (and be killed) in a separate thread? Or is this impossible because of inherent limitations to Tkinter? Gregor From arcege@speakeasy.net Sun Oct 21 13:59:13 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Sun, 21 Oct 2001 08:59:13 -0400 Subject: [Tutor] Developing GUI-programs using IDLE In-Reply-To: <4.2.0.58.20011020194547.019d4330@pop3.norton.antivirus>; from urnerk@qwest.net on Sat, Oct 20, 2001 at 07:48:34PM -0700 References: <009601c159c2$80edcc40$1664a8c0@mega> <4.2.0.58.20011020194547.019d4330@pop3.norton.antivirus> Message-ID: <20011021085913.A8718@speakeasy.net> On Sat, Oct 20, 2001 at 07:48:34PM -0700, Kirby Urner wrote: > >Otherwise developing GUI-programs with IDLE would be rather > >uncomfortable. > > I think you will find that developing GUI-programs > (that use Tk) in IDLE *is* rather uncomfortable. > That's a drawback of IDLE. > > I agree with the earlier poster: go ahead and > edit/reload in IDLE, but test with another icon > that bypasses IDLE. The version of IDLE that comes with Python 2.1 does not seem to have a problem if your program explicitly creates a new Tk() object and you use that. (Remember that you can have multiple root windows each with its own mainloop.) Also, remember that Python does come with a good text-based debugger ("pdb"), which is one of the "nice reasons" that people use IDLE. Myself, I rarely use IDLE; pdb has fewer problems with reload(). -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | | Ailment info: http://www.speakeasy.org/~arcege/michaelwatch.html | From rufmetal@home.com Sun Oct 21 18:17:02 2001 From: rufmetal@home.com (Chris Keelan) Date: Sun, 21 Oct 2001 12:17:02 -0500 Subject: [Tutor] a strange(r's) question In-Reply-To: <20011020213609.B25563@harmony.cs.rit.edu> References: <005301c159b6$fe3e24d0$1664a8c0@mega> <20011020213609.B25563@harmony.cs.rit.edu> Message-ID: <01102112170200.04924@tygesen> On Sat, 20 Oct 2001, dman wrote: | It is an exercise in architecture more than implementation. When you say "architecture" are you using it in the same sense as "program design" or in the hardware sense of "x86"? - Chris 'doesn't have the benefit of a CS background and frequently gets lost in the barrens' From nhytro-python@web.de Sun Oct 21 17:42:32 2001 From: nhytro-python@web.de (Sharriff Aina) Date: Sun, 21 Oct 2001 18:42:32 +0200 Subject: [Tutor] Displaying data produced from commandline in Tkinter Message-ID: <200110211642.f9LGgWu03193@mailgate5.cinetic.de> Hi guys! my Grayson Tkinter book is still in backorder :-(, but in the meantime, can someone tel me how to display data that continuously changes on the commandline in Tkinter? I have an idea how that could be don for a command that is run and piped to tkinter, but not if the commandline process verbosely outputs comments. Ideas? Thanks in advance Sharriff _______________________________________________________________________ 1.000.000 DM gewinnen - kostenlos tippen - http://millionenklick.web.de IhrName@web.de, 8MB Speicher, Verschluesselung - http://freemail.web.de From arcege@speakeasy.net Sun Oct 21 18:13:03 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Sun, 21 Oct 2001 13:13:03 -0400 Subject: [Tutor] Displaying data produced from commandline in Tkinter In-Reply-To: <200110211642.f9LGgWu03193@mailgate5.cinetic.de>; from nhytro-python@web.de on Sun, Oct 21, 2001 at 06:42:32PM +0200 References: <200110211642.f9LGgWu03193@mailgate5.cinetic.de> Message-ID: <20011021131303.B8718@speakeasy.net> On Sun, Oct 21, 2001 at 06:42:32PM +0200, Sharriff Aina wrote: > Hi guys! my Grayson Tkinter book is still in backorder :-(, but in the meantime, can someone tel me how to display data that continuously changes on the commandline in Tkinter? I have an idea how that could be don for a command that is run and piped to tkinter, but not if the commandline process verbosely outputs comments. Ideas? > You probably want to look into the createfilehandler() function in the Tkinter._tkinter module. import os, Tkinter # keep sending any lines that are written to /var/log/messages file = os.popen('tail -f /var/log/messages') textbox = Text(None) textbox.pack() def getline(inputfile, mask, widget=textbox): line = inputfile.readline() widget.insert(Tkinter.END, line) # line already has a newline Tkinter._tkinter.createfilehandler(file, Tkinter._tkinter.READABLE, getline) textbox.mainloop() Each time through the mainloop, Tkinter will also check to see if there is data coming from the file you specify and the function specified is called with the data file and with a mask (READABLE, WRITABLE, etc.). -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From dsh8290@rit.edu Sun Oct 21 20:02:04 2001 From: dsh8290@rit.edu (dman) Date: Sun, 21 Oct 2001 15:02:04 -0400 Subject: [Tutor] a strange(r's) question In-Reply-To: <01102112170200.04924@tygesen>; from rufmetal@home.com on Sun, Oct 21, 2001 at 12:17:02PM -0500 References: <005301c159b6$fe3e24d0$1664a8c0@mega> <20011020213609.B25563@harmony.cs.rit.edu> <01102112170200.04924@tygesen> Message-ID: <20011021150204.A28574@harmony.cs.rit.edu> On Sun, Oct 21, 2001 at 12:17:02PM -0500, Chris Keelan wrote: | On Sat, 20 Oct 2001, dman wrote: | | It is an exercise in architecture more than implementation. | | When you say "architecture" are you using it in the same sense as "program | design" Yes. I'm a "Software Engineering" major. Architectures differ from Design Patterns in that architectures are a higher level overview of how modules (in a general, not python-specific sense) interact with each other. Design patterns are patterns for how the internals of a module are designed. Design patterns are well explained in the "Gang of Four" book "Design Patterns" published by Addison Wesley. A highly recommended book. The textbook for this class is "Software Engineering in Practice" by Len Bass, Paul Clements and Rick Kazman. It is also published by Addison-Wesley. If you want more information on this course (titled "Principles of Software Architecture") see http://www.se.rit.edu/~se440/ An example of what I was refering to above : We have to include support for other network protcols such as MS Exchange in the architecture, but we don't have to include that in the implementation. We have to show, in our presentations, how it would be easy to add (for example) Exchange support to the implementation because the architecture supports it. | or in the hardware sense of "x86"? Hardware has an architecture (the high-level design for how the processor will work), though those are necessarily different from software architectures. -D From dsh8290@rit.edu Sun Oct 21 20:11:29 2001 From: dsh8290@rit.edu (dman) Date: Sun, 21 Oct 2001 15:11:29 -0400 Subject: [Tutor] Re: Developing GUI-programs using IDLE In-Reply-To: <014001c15a28$70aa1170$1664a8c0@mega>; from glingl@aon.at on Sun, Oct 21, 2001 at 02:03:47PM +0200 References: <014001c15a28$70aa1170$1664a8c0@mega> Message-ID: <20011021151129.B28574@harmony.cs.rit.edu> On Sun, Oct 21, 2001 at 02:03:47PM +0200, Gregor Lingl wrote: | What a pity! | Nevertheless, thanks to both of you. | | I like to use it in interactive mode to show the working | of Tkinter. It's quite nice to observe Tkinter-Objects react on | single (e.g. config-) statements step by step, and it helps to learn | Tkinter. | | I wonder, if it would be possible to enhance IDLE (which (version 0.8) | still seems to be in an unmature state) by some sort of multi-threading | mechanism, so GUI-apps could run (and be killed) in a separate thread? Not with threads. Threads can't be killed externally, they can only be stopped "nicely" internally. The reason for that is the "other" thread shares the same memory and resources, etc, with the rest of the threads. The kernel can't determine which resources to release, etc, because it doesn't know what belongs to that thread and what belongs to the other threads. Some people contend that threads are bad hacks and that light-weight processes and IPC should be used instead of threads. A separate process can be killed because it has its own set of resources and the kernel can clean up after it when another process sends it SIGKILL. | Or is this impossible because of inherent limitations to Tkinter? It is just much more complicated and no one has yet bothered to add external process support to any of the existing IDEs. Everyone has so far found it much easier to just run the app separately. HTH, -D From dyoo@hkn.eecs.berkeley.edu Sun Oct 21 20:54:41 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 21 Oct 2001 12:54:41 -0700 (PDT) Subject: [Tutor] Re: Developing GUI-programs using IDLE In-Reply-To: <014001c15a28$70aa1170$1664a8c0@mega> Message-ID: > I like to use it in interactive mode to show the working > of Tkinter. It's quite nice to observe Tkinter-Objects react on > single (e.g. config-) statements step by step, and it helps to learn > Tkinter. I do remember hearing about an official IDLE fork that was, among other things, meant to fix this strange behavior: http://idlefork.sourceforge.net You might want to talk with the IDLE folks there; if they haven't fixed this, perhaps a gentle prod will get someone motivated enough to fix this. *grin* Good luck to you! From amosbrooks@home.com Sun Oct 21 21:31:31 2001 From: amosbrooks@home.com (Amos Brooks) Date: Sun, 21 Oct 2001 16:31:31 -0400 Subject: [Tutor] Advertisement: Get in on this NOW... References: Message-ID: <009901c15a6f$5f094fc0$266a0841@nhven1.ct.home.com> Hi, Is anyone reporting this stuff as spam ... This stuff really drives me nuts. I'd report it mysely but I just wanted to know if someone is already working on it. from the peanut gallery, Amos Brooks ----- Original Message ----- From: <55551212@email.com> To: Sent: Saturday, October 20, 2001 2:31 AM Subject: [Tutor] Advertisement: Get in on this NOW... > > > Dear Future Millionaire: > > I'll make you a promise. READ THIS E-MAIL TO THE END! - follow what it > says to the letter - and you will not worry whether a RECESSION is coming > or not, > who is President, or whether you keep your current job or not. Yes, I know > what > you are thinking. I never responded to one of these before either. One day > though, something just said "you throw away $25.00 going to a movie for 2 > hours > with your wife". "What the heck." Believe me, no matter where you believe > "those feelings" come from, I thank goodness every day that I had that > feeling. > I cannot imagine where I would be or what I would be doing had I not. Read > on. It's true. Every word of it. It is legal. I checked. Simply because > you > are buying and selling something of value. > > AS SEEN ON NATIONAL TV: > > Making over half million dollars every 4 to 5 months from your home. > > THANK'S TO THE COMPUTER AGE AND THE INTERNET ! > ================================================== > BE AN INTERNET MILLIONAIRE LIKE OTHERS WITHIN A YEAR!!! > > Before you say ''Bull'', please read the following. This is the letter > you have been hearing about on the news lately. Due to the popularity of > this > letter on the Internet, a national weekly news program recently devoted > anentire > show to the investigation of this program described below, to see if it > really > can make people money. The show also investigated whether or not the > program > was legal. > > Their findings proved once and for all that there are ''absolutely NO > Laws prohibiting the participation in the program and if people can "follow > the simple instruction" they are bound to make some mega bucks with only > $25 > out of pocket cost''. > DUE TO THE RECENT INCREASE OF POPULARITY & RESPECT THIS > PROGRAM HAS ATTAINED, IT IS CURRENTLY WORKING BETTER THAN EVER. > > This is what one had to say: '' Thanks to this profitable opportunity". I > was approached many times before but each time I passed on it. I am so glad > I > finally joined just to see what one could expect in return for the > minimal effort and money required. To my astonishment, I received a total $ > 610,470.00 in 21 weeks, with money still coming in''. Pam Hedland, Fort > Lee, New > Jersey. > ================================================== > Another said: "this program has been around for a long time but I never > believed in it. But one day when I received this again in the mail I > decided to gamble my $25 on it. I followed the simple instructions and > walaa ..... 3 > weeks later the money started to come in. First month I only made $240.00 > but > the next 2 months after that I made a total of $290,000.00. So far, in the > past 8 > months by re-entering the program, I have made over $710,000.00 and I am > playing > it again. The key to success in this program is to follow the simple steps > and NOT change > anything.'' More testimonials later but first, ======= > > ==== PRINT THIS NOW FOR YOUR FUTURE REFERENCE ==== > $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ > > If you would like to make at least $500,000 every 4 to 5 months easily > and comfortably, please read the following...THEN READ IT AGAIN and AGAIN > !!! > > $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ > > FOLLOW THE SIMPLE INSTRUCTION BELOW AND YOUR FINANCIAL DREAMS > WILL COME TRUE, GUARANTEED! > > INSTRUCTIONS: > > =====Order all 5 reports shown on the list below ===== > > For each report, send $5 CASH, THE NAME & NUMBER OF THE REPORT YOU > ARE ORDERING and YOUR E-MAIL ADDRESS to the person whose name appears > ON THAT LIST next to the report. MAKE SURE YOUR RETURN ADDRESS IS ON > YOUR ENVELOPE TOP LEFT CORNER in case of any mail problems. > > ===WHEN YOU PLACE YOUR ORDER, MAKE SURE === > ===YOU ORDER EACH OF THE 5 REPORTS! === > You will need all 5 reports so that you can save them on your computer > and resell them. YOUR TOTAL COST $5 X 5 = $25.00. > > Within a few days you will receive, via e-mail, each of the 5 reports > from these 5 different individuals. Save them on your computer so they will > be > accessible for you to send to the 1,000's of people who will order them > from you. > Also make a floppy of these reports and keep it on your desk in case > something > happens to your computer. > > IMPORTANT - DO NOT alter the names of the people who are listed next to > each report, or their sequence on the list, in any way other than what is > instructed below in step '' 1 through 6 '' or you will loose out on the > majority of > your profits. Once you understand the way this works, you will also see how > it > does not work if you change it. Remember, this method has been tested, and > if > you alter it, it will NOT work !!! People have tried to put their > friends/relatives names on all five thinking they could get all the money. > But it does not > work this way. Believe us, some have tried to be greedy and then nothing > happened. So Do Not try to change anything other than what is instructed. > Because if > you do, it will not work for you. Remember, honesty reaps the reward!!! > This IS a > legitimate BUSINESS. You are offering a product for sale and getting paid > for it. Treat it as such and you will be VERY profitable in a short period > of > time. > > 1.. After you have ordered all 5 reports, take this advertisement and > REMOVE the name & address of the person in REPORT # 5. This person has > made it through the cycle and is no doubt counting their fortune. > > 2..Move the name & address in REPORT # 4 down TO REPORT # 5. > > 3.. Move the name & address in REPORT # 3 down TO REPORT # 4. > > 4.. Move the name & address in REPORT # 2 down TO REPORT # 3. > > 5.. Move the name & address in REPORT # 1 down TO REPORT # 2 > > 6.... Insert YOUR name & address in the REPORT # 1 Position. > > PLEASE MAKE SURE you copy every name & address ACCURATELY! This is > critical to YOUR success. > > ================================================== > **** Take this entire letter, with the modified list of names, and save > it on your computer. DO NOT MAKE ANY OTHER CHANGES. > > Save this on a disk as well just in case if you loose any data. To assist > you with marketing your business on the internet, the 5 reports you > purchase will provide you with invaluable marketing information which > includes how > to send bulk e-mails legally, where to find thousands of free classified > ads > and much more. There are 2 Primary methods to get this venture going: > > METHOD # 1: BY SENDING BULK E-MAIL LEGALLY > ================================================== > > Let's say that you decide to start small, just to see how it goes, and we > will assume You and those involved send out only 5,000 e-mails each. > Let's also assume that the mailing receive only a 0.2% (2/10 of 1%) > response (the > response could be much better but lets just say it is only 0.2%). Also many > people > will send out hundreds of thousands e-mails instead of only 5,000 each). > Continuing with this example, you send out only 5,000 e-mails. > > With a 0.2% response, that is only 10 orders for report # 1. Those 10 > people responded by sending out 5,000 e-mail each for a total of 50,000. > Out of > those 50,000 e-mails only 0.2% responded with orders. That's=100 people > responded and ordered Report # 2. > > Those 100 people mail out 5,000 e-mails each for a total of 500,000 > e-mails. The 0.2% response to that is 1000 orders for Report # 3. > > Those 1000 people send 5,000 e-mail each for a total of 5 million > e-mail sent out. The 0.2% response is 10,000 orders for Report # 4. > > Those 10,000 people send out 5,000 e-mails each for a total of 50,000,000 > (50 million) e-mails. The 0.2% response to that is 100,000 orders for > Report > # 5. > > THAT'S 100,000 ORDERS TIMES $5 EACH = $500,000.00 (half a million dollars). > > Your total income in this example is: 1..... $50 + 2..... $500 + 3..... > $5,000 + 4..... $50,000 + 5.... $500,000 .... Grand Total=$555,550.00 > > NUMBERS DO NOT LIE. GET A PENCIL & PAPER AND FIGURE OUT THE > WORST POSSIBLE RESPONSES AND NO MATTER HOW YOU CALCULATE IT, YOU WILL STILL > MAKE A LOT OF MONEY! > ================================================== > > REMEMBER FRIEND, THIS IS ASSUMING ONLY 10 PEOPLE ORDERING OUT OF > 5,000 YOU MAILED TO. Dare to think for a moment what would happen if > everyone or > half or even one 4th of those people mailed 100,000 e-mails each or more? > There > are over 150 million people on the Internet worldwide and counting, with > thousands > more coming on line every day. Believe me, many people will do just that, > and > more! > > METHOD # 2: BY PLACING FREE ADS ON THE INTERNET > ================================================== > > Advertising on the net is very, very inexpensive and there are hundreds > of FREE places to advertise. Placing a lot of free ads on the Internet will > easily get a larger response. We strongly suggest you start with Method # 1 > and add > METHOD #2 as you go along. For every $5 you receive, all you must do is > e-mail > them the Report they ordered. That's it. Always provide same day service on > all > orders. > > This will guarantee that the e-mail they send out, with your name and > address on it, will be prompt because they can not advertise until they > receive the report. > > ===========AVAILABLE REPORTS ==================== > The reason for the "cash" is not because this is illegal or somehow > "wrong". It is simply about time. Time for checks or credit cards to be > cleared or > approved, etc. Concealing it is simply so no one can SEE there is money in > the > envelope and steal it before it gets to you. > > ORDER EACH REPORT BY ITS NUMBER & NAME ONLY. Notes: Always send $5 > cash (U.S. CURRENCY) for each Report. Checks NOT accepted. Make sure the > cash is > concealed by wrapping it in at least 2 sheets of paper. On one of those > sheets of > paper, Write the NUMBER & the NAME of the Report you are ordering, YOUR > E-MAIL > ADDRESS and your name and postal address. > > PLACE YOUR ORDER FOR THESE REPORTS NOW : > ================================================== > REPORT# 1: 'The Insider's Guide To Advertising for Free On The Net > > Order Report #1 from > > Keith Gilbert > 2822 N. Ridgewood St. > Santa Ana, CA 92705 > USA > > ________________________________________________________ > > REPORT # 2: The Insider's Guide To Sending Bulk Email On The Net > > Order Report # 2 from: > > Steve Stwan > P.O. Box 23923 > Federal Way, WA 98093 > USA > > _________________________________________________________________ > > REPORT # 3: Secret To Multilevel Marketing On The Net > > Order Report # 3 from : > > Craig Wuthrich > 2390 Falls Ave. E. > Twin Falls, ID 83301 > USA > > ______________________________________________________ > > REPORT # 4: How To Become A Millionaire Using MLM & The Net > > Order Report # 4 from: > > S. Wong > 50 Burnhamthorpe Rd. West #401 > Mississauga, Ontario, L5B 3C2 > Canada > > > _______________________________________________________ > > REPORT #5: How To Send Out One Million Emails For Free > > Order Report # 5 From: > > Zach Simmons > 2135 Springwood > Carrollton, TX 75006 > USA > > _____________________________________________________ > $$$$$$$$$ YOUR SUCCESS GUIDELINES $$$$$$$$$$$ > > Follow these guidelines to guarantee your success: > > === If you do not receive at least 10 orders for Report #1 within 2 > weeks, continue sending e-mails until you do. > > === After you have received 10 orders, 2 to 3 weeks after that you should > receive 100 orders or more for REPORT # 2. If you did not, continue > advertising or sending e-mails until you do. > > **Once you have received 100 or more orders for Report # 2, YOU CAN > RELAX, because the system is already working for you, and the cash will > continue > to roll in ! THIS IS IMPORTANT TO REMEMBER: Every time your name is moved > down on the list, you are placed in front of a Different report. > > You can KEEP TRACK of your PROGRESS by watching which report people are > ordering from you. IF YOU WANT TO GENERATE MORE INCOME SEND ANOTHER > BATCH OF E-MAILS AND START THE WHOLE PROCESS AGAIN. There is NO LIMIT > to the income you can generate from this business !!! > ================================================= > FOLLOWING IS A NOTE FROM THE ORIGINATOR OF THIS PROGRAM: You have > just received information that can give you financial freedom for the rest > of your > life, with NO RISK and JUST A LITTLE BIT OF EFFORT. You can make more money > in the > next few weeks and months than you have ever imagined. Follow the program > EXACTLY > AS INSTRUCTED. Do Not change it in any way. It works exceedingly well as it > is now. > > Remember to e-mail a copy of this exciting report after you have put your > name and address in Report #1 and moved others to #2 .....# 5 as instructed > above. One of the people you send this to may send out 100,000 ormore > e-mails > and your name will be on every one of them. Remember though, the more you > send out > the more potential customers you will reach. So my friend, I have given you > the ideas, information, materials and opportunity to become financially > independent. > IT IS UP TO YOU NOW ! > =============MORE TESTIMONIALS=============== > '' My name is Mitchell. My wife, Jody and I live in Chicago. I am an > accountant with a major U.S. Corporation and I make pretty good money. > When I received this program I grumbled to Jody about receiving ''junk > mail''. I > made fun of the whole thing, spouting my knowledge of the population and > percentages involved. I ''knew'' it wouldn't work. Jody totally ignored my > supposed > intelligence and few days later she jumped in with both feet. I made > merciless fun of her, and was ready to lay the old ''I told you so'' on her > when > the thing didn't work. Well, the laugh was on me! Within 3 weeks she had > received > 50 responses. Within the next 45 days she had received total $ 147,200.00 > ......... all cash! I was shocked. I have joined Jodyin her ''hobby''. > Mitchell Wolf M.D., Chicago, Illinois > ================================================ > '' Not being the gambling type, it took me several weeks to make up my > mind to participate in this plan. But conservative as I am, I decided that > the > initial investment was so little that there was just no way that I wouldn't > get > enough orders to at least get my money back''. '' I was surprised when I > found > my medium size post office box crammed with orders. I made $319,210.00 in > the first 12 weeks. The nice thing about this deal is that it does not > matter where > people live. There simply isn't a better investment with a faster return > and so > big''. Dan Sondstrom, Alberta, Canada > ================================================= > '' I had received this program before. I deleted it, but later I wondered > if I should have given it a try. Of course, I had no idea who to contact to > get another copy, so I had to wait until I was e-mailed again by someone > else.........11 months passed then it luckily came again...... I did not > delete this one! I made more than $490,000 on my first try and all the > money > came within 22 weeks''. Susan De Suza, New York, N.Y. > ================================================= > '' It really is a great opportunity to make relatively easy money with > little cost to you. I followed the simple instructions carefully and > within 10 days the money started to come in. My first month I made $ 20, > 560.00 and > by the end of third month my total cash count was $ 362,840.00. Life is > beautiful, Thanx to internet''. Fred Dellaca, Westport, New Zealand > ================================================= > > ORDER YOUR REPORTS TODAY AND GET STARTED ON YOUR ROAD TO > FINANCIAL > FREEDOM ! > > ================================================= > If you have any questions of the legality of this program, contact the > Office of Associate Director for Marketing Practices, Federal Trade > Commission, Bureau of Consumer Protection, Washington, D.C. > > ================================================= > > ONE TIME MAILING, NO NEED TO REMOVE > > ================================================= > > This message is sent in compliance of the proposed bill SECTION 301, > paragraph (a)(2)(C) of S. 1618. Further transmission to you by the sender > of this email may be stopped at no cost to you by sending a reply to: > coho2@ziplip.com with the word REMOVE in the subject line. This message is not > intended for residents in the State of Washington, screening of addresses has been done > to the best of our technical ability. > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From urnerk@qwest.net Sun Oct 21 21:48:47 2001 From: urnerk@qwest.net (Kirby Urner) Date: Sun, 21 Oct 2001 13:48:47 -0700 Subject: [Tutor] Advertisement: Get in on this NOW... In-Reply-To: <009901c15a6f$5f094fc0$266a0841@nhven1.ct.home.com> References: Message-ID: <4.2.0.58.20011021134712.019deda0@pop3.norton.antivirus> At 04:31 PM 10/21/2001 -0400, Amos Brooks wrote: >Hi, > Is anyone reporting this stuff as spam ... This stuff really drives me >nuts. Quoting the whole long spam back at us via the list is not a way to fight it, but is to be a spammer yourself. A few lines to let us know what you're referring to would have been sufficient. Kirby From nhytro-python@web.de Sun Oct 21 22:27:29 2001 From: nhytro-python@web.de (Sharriff Aina) Date: Sun, 21 Oct 2001 23:27:29 +0200 Subject: [Tutor] Tkinter class member question Message-ID: <200110212127.f9LLRTu03772@mailgate5.cinetic.de> I=B4m still trying to know how to encompass my tkinter widgets and sciots in= classes. Given: #### code start class Mydialog: ....def =5Finit=5F(self, master): ........self.top=3DTkinter.Toplevel(master) ........self.name=3DTkinter.StringVar() ........entry =3DTkinter.Entry(self.top, textvariable=3Dself.name)## why=3F=3F ##### code snippet end why does the creation of the Entry widget start with "entry =3D" instead of = "self.entry" =3F I thought all class variables have to start with self=3F Furt= hermore, is it wise to write global functions or to embed the functions in= the widgets of the classes calling the functions=3F My head is spinning at the moment... Thanks for any help and tips Sharriff =5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F 1.000.000 DM gewinnen - kostenlos tippen - http://millionenklick.web.de IhrName@web.de, 8MB Speicher, Verschluesselung - http://freemail.web.de From alan.gauld@bt.com Sun Oct 21 22:27:10 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 21 Oct 2001 22:27:10 +0100 Subject: [Tutor] Help on Arrays? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C00C@mbtlipnt02.btlabs.bt.co.uk> > Any reference to tutorial/examples on creation and use of > *Arrays* in Python Try my tutor, specifically the raw materials topic which covers arrays. http://www.freenetpages.co.uk/hp/alan.gauld/ Alan g From alan.gauld@bt.com Sun Oct 21 22:36:21 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 21 Oct 2001 22:36:21 +0100 Subject: [Tutor] one more question on a word in a specific place in a line Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C00D@mbtlipnt02.btlabs.bt.co.uk> > I am currently reading a text file that is essentially a > weather report. It looks as follows: > > 12-23-01 > KPVD yyyyyy/ggggg/kkkkkkk/lllllllllll > Sometimes, however, a different weather text may > have some additional text that spills into the > next line. So how do you know that? By looking at the pattern you can tell. So you have to do "pattern matching" in your program to look for the same pattern that your brain sees. My guess in this case is its the bit with the slashes in. So test each line to see if it has '/' in it, if so grab the first word... If thats not precise enough increase the pattern complexity - which probably takes you into regular expression territory. HTH, Alan g. From alan.gauld@bt.com Sun Oct 21 22:41:25 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 21 Oct 2001 22:41:25 +0100 Subject: [Tutor] a strange(r's) question Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C00E@mbtlipnt02.btlabs.bt.co.uk> ------_=_NextPart_001_01C15A79.21F4AB70 Content-type: text/plain; charset="iso-8859-1" Tkinter is pronounced correctly in English. Well I say "Tee Kay inter" but I've no idea how anyone else says it :-) Alan G ------_=_NextPart_001_01C15A79.21F4AB70 Content-type: text/html; charset="iso-8859-1"
       Tkinter
 
is pronounced correctly in English.
Well I say "Tee Kay inter" but I've no idea how
anyone else says it :-)
 
Alan G
 
------_=_NextPart_001_01C15A79.21F4AB70-- From alan.gauld@bt.com Sun Oct 21 22:49:46 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 21 Oct 2001 22:49:46 +0100 Subject: [Tutor] Re: Developing GUI-programs using IDLE Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C00F@mbtlipnt02.btlabs.bt.co.uk> > I wonder, if it would be possible to enhance IDLE There are folks working on making ID:E multi threaded, but... > Or is this impossible because of inherent limitations to Tkinter? ...it doesn't help Tkinter because the limitation of one mainloop() is (I believe) in the underlying Tk toolkit not even in Tkinter. BTW You can still use the interactive prompt to develop tkinter progs, you just have to use the command line version. If you use NT or Cygwin then you get the last command recall etc. So its quite usable... Otherwise as already suggested use IDLE as editor and the command prompt for testing - F3 is your friend! :-) Alan g From arcege@speakeasy.net Sun Oct 21 23:16:23 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Sun, 21 Oct 2001 18:16:23 -0400 Subject: [Tutor] Tkinter class member question In-Reply-To: <200110212127.f9LLRTu03772@mailgate5.cinetic.de>; from nhytro-python@web.de on Sun, Oct 21, 2001 at 11:27:29PM +0200 References: <200110212127.f9LLRTu03772@mailgate5.cinetic.de> Message-ID: <20011021181623.C8718@speakeasy.net> On Sun, Oct 21, 2001 at 11:27:29PM +0200, Sharriff Aina wrote: > I=B4m still trying to know how to encompass my tkinter widgets and scio= ts in classes. >=20 > Given: >=20 > #### code start > class Mydialog: > ....def _init_(self, master): > ........self.top=3DTkinter.Toplevel(master) > ........self.name=3DTkinter.StringVar() > ........entry =3DTkinter.Entry(self.top, textvariable=3Dself.name)## wh= y?? > ##### code snippet end >=20 > why does the creation of the Entry widget start with "entry =3D" instea= d of "self.entry" ? I thought all class variables have to start with self= ? Furthermore, is it wise to write global functions or to embed the funct= ions in the widgets of the classes calling the functions? The reason is probably because the data that is required is the contents of the string Tkinter variable. Unless there is a need for the program to manipulate the widget (not the contents of the variable) after its creation, there is no need to keep the reference. -Arcege --=20 +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From urnerk@qwest.net Sun Oct 21 23:54:21 2001 From: urnerk@qwest.net (Kirby Urner) Date: Sun, 21 Oct 2001 15:54:21 -0700 Subject: [Tutor] Re: Developing GUI-programs using IDLE In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C00F@mbtlipnt02.btlabs .bt.co.uk> Message-ID: <4.2.0.58.20011021154505.019e6470@pop3.norton.antivirus> > >version. If you use NT or Cygwin then you get the last >command recall etc. So its quite usable... Are you referring to Python in shell mode, or the the OS command line? Ordinary WinME (not sure about 95/98) has a doskey buffer of previous command lines. You can launch doskey if it's not the default. You can even do a kind of aliasing, ala bash, by entering > doskey d = dir /w or > doskey p = c:\python21\python $* or whatever. Then just go: > d to get a dir, or > p myfile.py arg1 arg2 to run a Python script. (there's a way to initialize all these upon hitting the MSDOS icon too (Python Programming on Win32, by Mark Hammond and Andy Robinson, O'Reilly, discusses these little tricks)). These are all ways of making the WinOS command line more usable. But the Python shell, without arrow-up, is quasi-unusable as an IDE, in my experience. But maybe in NT or Cygwin this limitation goes away? Kirby From dsh8290@rit.edu Mon Oct 22 02:37:54 2001 From: dsh8290@rit.edu (dman) Date: Sun, 21 Oct 2001 21:37:54 -0400 Subject: [Tutor] Re: Developing GUI-programs using IDLE In-Reply-To: <4.2.0.58.20011021154505.019e6470@pop3.norton.antivirus>; from urnerk@qwest.net on Sun, Oct 21, 2001 at 03:54:21PM -0700 References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C00F@mbtlipnt02.btlabs.bt.co.uk> <4.2.0.58.20011021154505.019e6470@pop3.norton.antivirus> Message-ID: <20011021213754.A2607@harmony.cs.rit.edu> On Sun, Oct 21, 2001 at 03:54:21PM -0700, Kirby Urner wrote: | | > | >version. If you use NT or Cygwin then you get the last | >command recall etc. So its quite usable... | | Are you referring to Python in shell mode, or the | the OS command line? Pyhton in shell mode, iff it is linked against GNU readline. | Ordinary WinME (not sure about 95/98) has a doskey | buffer of previous command lines. You can launch 95/98 do have the previous command via F3, I think, and the same one char at a time with F1. | doskey if it's not the default. Doskey (or its predecessor Commando) rule when the shell doesn't provide it natively. (that is, MS shells, bash already has readline) -D From pythonpython@hotmail.com Mon Oct 22 03:50:17 2001 From: pythonpython@hotmail.com (Hy Python) Date: Mon, 22 Oct 2001 02:50:17 +0000 Subject: [Tutor] how to convert a number into a string Message-ID: Could anyone tell me how to convert a number into a string? Thanks a lot! Hy _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp From rufmetal@home.com Mon Oct 22 04:55:51 2001 From: rufmetal@home.com (Chris Keelan) Date: Sun, 21 Oct 2001 22:55:51 -0500 Subject: [Tutor] how to convert a number into a string In-Reply-To: References: Message-ID: <01102122555102.00920@tygesen> On Sun, 21 Oct 2001, Hy Python wrote: Yay! Finally one I can answer. > Could anyone tell me how to convert a number into a string? > Thanks a lot! Use str(n), e.g.: n = aNumber stringN=str(aNumber) - Chris From lonetwin@yahoo.com Mon Oct 22 07:01:19 2001 From: lonetwin@yahoo.com (lonetwin) Date: Mon, 22 Oct 2001 11:31:19 +0530 Subject: OT : Re: [Tutor] a strange(r's) question In-Reply-To: <00a201c159d0$76dc4020$3ba616ca@ACE> References: <005301c159b6$fe3e24d0$1664a8c0@mega> <00a201c159d0$76dc4020$3ba616ca@ACE> Message-ID: <01102211311901.01208@mercury.worli> Hi everybody, Just wanted to share this ...I(along with some o' ppl here [Bombay-India]) were so used to pronouncing it is TINK-ter (as in tinker with tink-ter) !!!! LOL !!! Peace Steve On Sunday 21 October 2001 07:04, you wrote: > Heh, there have been plenty of um 'discussions' about this with me and > friends, but to quote a guy who should know alot about it - 'Tkinter > (pronounced tea-kay-inter), ...'. That's from John Grayson, the back cover > of his book 'Python and Tkinter programming'. > Although I must admit I do usually pronounce it t-kinter in my mind :) > > HTH, > Glen > > As my native language is German, I don't > know how > > Tkinter > > is pronounced correctly in English. > > Thanks for answering to this somewhat > off-programming question > > Gregor Lingl > > P.S. As I'm teaching Python, I have to > talk about it. ---------------------------------------------- Every oak tree started out as a couple of nuts who stood their ground. Anonymous ---------------------------------------------- From alan.gauld@bt.com Mon Oct 22 10:41:11 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 22 Oct 2001 10:41:11 +0100 Subject: [Tutor] Re: Developing GUI-programs using IDLE Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C010@mbtlipnt02.btlabs.bt.co.uk> > Are you referring to Python in shell mode, or the > the OS command line? Sorrey, not clear. I meant the shell mode. Yes DOSKEY is a big help but doesn't work in Python unfortunately whereas in NT it does. > is quasi-unusable as an IDE, in my experience. But > maybe in NT or Cygwin this limitation goes away? I haven't actually tried cygwin python but I believe it has full GNU readline capability so is as good as an xterm... NT isn't that good but at least you get up arrow command recall and basic line editing which is a big help... Presumably soon WinXP will finally offer these to home users too! Alan G. From kjayasurya@hotmail.com Mon Oct 22 10:53:24 2001 From: kjayasurya@hotmail.com (jayasurya kanukurthy) Date: Mon, 22 Oct 2001 15:23:24 +0530 Subject: [Tutor] is ok Message-ID: _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp From dyoo@hkn.eecs.berkeley.edu Mon Oct 22 22:39:45 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 22 Oct 2001 14:39:45 -0700 (PDT) Subject: [Tutor] AIML or ALICE implemented in Python? (fwd) Message-ID: Dear John, I think you meant to send this off to the Tutor list at: tutor@python.org. I'll forward your post there. Hope this helps! ---------- Forwarded message ---------- Date: Mon, 22 Oct 2001 22:31:44 +0100 From: John Precedo To: tutor-admin@python.org Subject: AIML or ALICE implemented in Python? Hi all. I've been looking into Artificial Intelligence (after hearing about this years Loebner Prize - it's a formalized Turing Test which happened at the Science Museum in London this year). Anyway, the winner was A.L.I.C.E - and she (or at least a de-personalized version called alicebot) is Open Source software that anyone can download. There is also AIML - the Artificial Intelligence Markup Language. The good news is that both of these are Open Source, released under the GNU General Public License. The bad news is that they are written in Java. (blech). Does anyone know of an Alice port in Python? Or an implementation of AIML in Python? Failing that, does anyone want to write one (and have the time and the skill, both of which I lack)? Considering the level of 'intelligence' currently in AI, could this be a project for 'Useless Python'? -- John Precedo (johnp@reportlab.com) Developer Reportlab Europe Ltd (http://www.reportlab.com) From dsh8290@rit.edu Mon Oct 22 23:05:17 2001 From: dsh8290@rit.edu (dman) Date: Mon, 22 Oct 2001 18:05:17 -0400 Subject: [Tutor] AIML or ALICE implemented in Python? (fwd) In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Mon, Oct 22, 2001 at 02:39:45PM -0700 References: Message-ID: <20011022180516.A8647@harmony.cs.rit.edu> | From: John Precedo | Date: Mon, 22 Oct 2001 22:31:44 +0100 ... | The good news is that both of these are Open Source, released under the GNU | General Public License. The bad news is that they are written in Java. | (blech). | | Does anyone know of an Alice port in Python? Or an implementation of AIML in | Python? Failing that, does anyone want to write one (and have the time and | the skill, both of which I lack)? Are these libraries or applications? Regardless, if you use the Java implementation of Python (http://jython.sourceforge.net) you get automatic use of any java class from python code. No glue necessary (it is all part of the interpreter). HTH, -D From tonycervone@netzero.net Tue Oct 23 00:56:08 2001 From: tonycervone@netzero.net (tonycervone) Date: Mon, 22 Oct 2001 19:56:08 -0400 Subject: [Tutor] concatenating two variables Message-ID: <000f01c15b55$1ffff360$278df4d1@w9y5d5> This is a multi-part message in MIME format. ------=_NextPart_000_000C_01C15B33.97B70BE0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I see how two strings(variables enclosed in quotation marks) can be = concatenated, but I am having difficulty doing it with two variables = representing strings in a print statement: print variable + variable # this statement does not provide any = spacing between the two strings, yet=20 I keep getting syntax errors whenever I try different combinations with = quotation marks.=20 So, if variable1 =3D good and variable2 =3D dog a print variable1 + variable2 outputs gooddog How do I output good dog with the above print statement? thanks. tony ------=_NextPart_000_000C_01C15B33.97B70BE0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I see how two strings(variables = enclosed in=20 quotation marks) can be concatenated, but I am having difficulty doing = it with=20 two variables representing strings in a print statement:
 
print  variable + = variable   #=20 this statement does not provide any spacing between the two strings,=20 yet 
 
I keep getting syntax errors whenever I = try=20 different combinations with quotation marks.
 
So, if  variable1 = =3D good  and =20 variable2 =3D dog   a
 
print variable1 + = variable2
 
outputs  gooddog
 
How do I output  good = dog   with the=20 above print statement?
 
 
 
thanks.
tony
------=_NextPart_000_000C_01C15B33.97B70BE0-- ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From kauphlyn@speakeasy.org Tue Oct 23 01:22:34 2001 From: kauphlyn@speakeasy.org (Daniel Coughlin) Date: Mon, 22 Oct 2001 17:22:34 -0700 (PDT) Subject: [Tutor] concatenating two variables In-Reply-To: <000f01c15b55$1ffff360$278df4d1@w9y5d5> Message-ID: you could try print varible1 + " " + variable2 or print variable1, variable2 or you could concatenate with interpolation print "%s %s" % (variable1, variable2) On Mon, 22 Oct 2001, tonycervone wrote: > I see how two strings(variables enclosed in quotation marks) can be concatenated, but I am having difficulty doing it with two variables representing strings in a print statement: > > print variable + variable # this statement does not provide any spacing between the two strings, yet > > I keep getting syntax errors whenever I try different combinations with quotation marks. > > So, if variable1 = good and variable2 = dog a > > print variable1 + variable2 > > outputs gooddog > > How do I output good dog with the above print statement? > > > > thanks. > tony > From rufmetal@home.com Tue Oct 23 02:23:45 2001 From: rufmetal@home.com (Chris Keelan) Date: Mon, 22 Oct 2001 20:23:45 -0500 Subject: [Tutor] concatenating two variables In-Reply-To: <000f01c15b55$1ffff360$278df4d1@w9y5d5> References: <000f01c15b55$1ffff360$278df4d1@w9y5d5> Message-ID: <01102220234500.01873@tygesen> On Mon, 22 Oct 2001, tonycervone wrote: 2 methods: A) >>>variable1='good', variable2 = ('good', 'dog') >>>print variable1 + " " + variable2 good dog B) >>print '%s %s" % (var1, var2) good dog > thanks. No thank you for asking something I can answer! - Chris Wesley Chun's "Core Python Programming", Chapter 6 and counting! From rufmetal@home.com Tue Oct 23 02:25:51 2001 From: rufmetal@home.com (Chris Keelan) Date: Mon, 22 Oct 2001 20:25:51 -0500 Subject: Fwd: Re: [Tutor] concatenating two variables Message-ID: <01102220255101.01873@tygesen> On Mon, 22 Oct 2001, tonycervone wrote: >2 methods: >A) >>>variable1='good', variable2 = ('good', 'dog') OOPS: that should be: >>> variable1 = 'good' ; variable2 = 'dog' I was trying to get fancy. You could always do it the safe way: >>>variable1 = 'good' >>>variable2 = 'dog' >>>print variable1 + " " + variable2 good dog B) >>print '%s %s" % (var1, var2) good dog > thanks. No thank you for asking something I can answer! - Chris Wesley Chun's "Core Python Programming", Chapter 6 and counting! ------------------------------------------------------- From toodles@yifan.net Tue Oct 23 01:35:29 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Tue, 23 Oct 2001 08:35:29 +0800 Subject: [Tutor] concatenating two variables References: <000f01c15b55$1ffff360$278df4d1@w9y5d5> Message-ID: <001801c15b5a$c64d1810$0300a8c0@sun> Hi Tony >So, if variable1 = good and variable2 = dog a > >print variable1 + variable2 > >outputs gooddog > >How do I output good dog with the above print statement? You want to replace the "+" with a comma. So use (for as many variables as you want to print):- print variable1,variable2, ... There's also other ways, like the following way using string formatting: print "%s %s"%(variable1,variable2) In that string at the beginning you can decide pricisely how the output will appear. It can have just the 1 space, or whatever else you want. I think this is fairly unecessary if you just want to print two variables though. :) Regards, Andrew >thanks. >tony From pemrograman@telkom.net Tue Oct 23 07:40:26 2001 From: pemrograman@telkom.net (Adinda-Praditya) Date: Tue, 23 Oct 2001 13:40:26 +0700 Subject: [Tutor] use of WxPython class, method, etc In-Reply-To: <4.2.0.58.20011012195907.00c55220@pop3.norton.antivirus> Message-ID: hi list,... i'm newbie in python world, tried to use wxpython. i read the manual (wxPython-docs-*.tar.gz), i think it's for C++ instead of python, (i don't know C++ :-( ) it said : wxStopWatch The wxStopWatch class allow you to measure time intervals. Include files See also ::wxStartTimer, ::wxGetElapsedTime, wxTimer Members wxStopWatch::wxStopWatch wxStopWatch::Pause wxStopWatch::Start wxStopWatch::Resume wxStopWatch::Time wxStopWatch::wxStopWatch wxStopWatch() Constructor. This starts the stop watch. --- still confuse using it. what does wxStopWatch::Start mean? i tried to make a stopwatch apps. what should i write? should i create panel first or not, how can i know that? I tried to use it in deferenct way, but i always get error. The most important thing is how can i understand the reference. which one is the method, function, and how to use it. Thank you very much, and sorry for my stupid questions. i use to write an old fashioned program (pascal 7.0) instead of OOP. Adinda From boud@valdyas.org Tue Oct 23 08:30:35 2001 From: boud@valdyas.org (Boudewijn Rempt) Date: Tue, 23 Oct 2001 09:30:35 +0200 Subject: [Tutor] use of WxPython class, method, etc In-Reply-To: References: Message-ID: <200110230730.f9N7Ud306490@calcifer.valdyas.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Tuesday 23 October 2001 08:40, Adinda-Praditya wrote: > hi list,... > > i'm newbie in python world, tried to use wxpython. i read > the manual (wxPython-docs-*.tar.gz), i think it's for C++ > instead of python, (i don't know C++ :-( ) > The wxWindows documentation, just like the Qt documentation, indeed refers to the C++ library. However, it's easy enough to mentally translate all double semi-colons and stuff to Python's dots. I think the appendix on reading C++ Qt documentation for use with PyQt at=20 http://stage.linuxports.com/pyqt/a6398.htm would be helpful for wxPython, too. There's some more discussion of the differences between C++ and Python in the book, but that is very much geared towards Qt and sip, and might not be relevant to wxPython at all. - --=20 Boudewijn Rempt | http://www.valdyas.org -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE71RyeN8fj6DnPxOgRAhEfAJwNJF/VDswVSMLTOPN0KCG3T11P5gCfaPIs um22duH3AIYoz9DV08/FRQo=3D =3D22rN -----END PGP SIGNATURE----- From pemrograman@telkom.net Tue Oct 23 09:18:12 2001 From: pemrograman@telkom.net (Adinda-Praditya) Date: Tue, 23 Oct 2001 15:18:12 +0700 Subject: [Tutor] use of WxPython class, method, etc In-Reply-To: <200110230730.f9N7Ud306490@calcifer.valdyas.org> Message-ID: Thanks alot Rempt, i'll read that. ps: i tried Boa's latest version. when i clicked the help button, it didn't run the help, or mannual or something like that. did i miss something with the installation? i use Linux 2.3.4 do you know where can i find the docs? I couldn't design my apps like any other builder. On Tue, 23 Oct 2001 09:30:35 +0200 Boudewijn Rempt wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > On Tuesday 23 October 2001 08:40, Adinda-Praditya wrote: > > hi list,... > > > > i'm newbie in python world, tried to use wxpython. i > read > > the manual (wxPython-docs-*.tar.gz), i think it's for > C++ > > instead of python, (i don't know C++ :-( ) > > > > The wxWindows documentation, just like the Qt > documentation, indeed > refers to the C++ library. However, it's easy enough to > mentally > translate all double semi-colons and stuff to Python's > dots. I think > the appendix on reading C++ Qt documentation for use with > PyQt at > http://stage.linuxports.com/pyqt/a6398.htm > would be helpful for wxPython, too. > > There's some more discussion of the differences between > C++ > and Python in the book, but that is very much geared > towards > Qt and sip, and might not be relevant to wxPython at all. > > - -- > > Boudewijn Rempt | http://www.valdyas.org > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.0.6 (GNU/Linux) > Comment: For info see http://www.gnupg.org > > iD8DBQE71RyeN8fj6DnPxOgRAhEfAJwNJF/VDswVSMLTOPN0KCG3T11P5gCfaPIs > um22duH3AIYoz9DV08/FRQo= > =22rN > -----END PGP SIGNATURE----- From dsh8290@rit.edu Tue Oct 23 14:01:54 2001 From: dsh8290@rit.edu (dman) Date: Tue, 23 Oct 2001 09:01:54 -0400 Subject: [Tutor] use of WxPython class, method, etc In-Reply-To: ; from pemrograman@telkom.net on Tue, Oct 23, 2001 at 01:40:26PM +0700 References: <4.2.0.58.20011012195907.00c55220@pop3.norton.antivirus> Message-ID: <20011023090154.A14184@harmony.cs.rit.edu> On Tue, Oct 23, 2001 at 01:40:26PM +0700, Adinda-Praditya wrote: | hi list,... | | i'm newbie in python world, tried to use wxpython. i read | the manual (wxPython-docs-*.tar.gz), i think it's for C++ | instead of python, (i don't know C++ :-( ) Yeah, the underlying wxWindows library is implemented in C++ and those people wrote most of the docs. C++ and Python are very similar (at least as far as the docs are concerned) and no one has spent the time to rewrite them to be python-specific. If you know C++ it isn't a problem. If not, well, ask when you have trouble and some people will explain it. There is also a mailing list dedicated to wxPython. | it said : | | wxStopWatch | The wxStopWatch class allow you to measure time intervals. | Include files | | See also | ::wxStartTimer, ::wxGetElapsedTime, wxTimer | Members | wxStopWatch::wxStopWatch | wxStopWatch::Pause | wxStopWatch::Start | wxStopWatch::Resume | wxStopWatch::Time | wxStopWatch::wxStopWatch wxStopWatch() | Constructor. This starts the stop watch. | --- | | still confuse using it. what does wxStopWatch::Start mean? It means that there is a method called "Start" that is inside the class called "wxStopWatch". The double-colon is called the "scope resolution operator". The dot ( '.' ) operator in Python performs the same functionality. Ignore the "include files" section. Also ignore anything that talks about memory management (new/delete, etc) -- python takes care of that for you. | i tried to make a stopwatch apps. what should i write? | should i create panel first or not, how can i know that? I | tried to use it in deferenct way, but i always get error. (note : all untested, but should give the general idea) import time import wx my_watch = wx.wxStopWatch() time.sleep( 2 ) print my_watch.Time() my_watch.Pause() time.sleep( 2 ) print my_watch.Time() my_watch.Resume() time.sleep( 2 ) print my_watch.Time() HTH, -D From pythontutor@infopackaging.com Tue Oct 23 16:00:23 2001 From: pythontutor@infopackaging.com (Troy Sorzano) Date: Tue, 23 Oct 2001 11:00:23 EDT Subject: [Tutor] TypeError: __str__ returned non-string (type DbiRaw) Message-ID: Hi All, I am a python newbie and having a little problem with dbiRaw. I am connecting via ODBC to a MS SQL 2000 database. The 3 column in the select statement is a BLOB that actually contains text. I want to convert that BLOB into a string but I can not figure out how to. The error I get is "TypeError: __str__ returned non-string (type DbiRaw)" Here is the code I am trying to convert the rec[2] into a string called blobstr then print it. blobstr = dbi.dbiRaw(rec[2]) print blobstr,'\n' Does anyone have an idea on how I can convert rec[2] which is a blob into a text string. I am sure it is simple to do in python but I have had no luck. Thanks for any info, Troy Sorzano P.S. I know mxODBC would work as it automatically converts blobs to strings. But the license is too restrictive for my simple project. P.P.S. Here is the full code. import dbi, odbc dbc = odbc.odbc('ipu_jslx2/sysdba/masterkey') crsr = dbc.cursor() crsr.execute( """ SELECT name, family, data FROM sysdba.plugin where type = 2 and userid = 'admin' ORDER BY name """ ) while 1: rec = crsr.fetchone() if not rec: break blobstr = dbi.dbiRaw(rec[2]) print blobstr,'\n' From smoynes@nexus.carleton.ca Tue Oct 23 17:33:39 2001 From: smoynes@nexus.carleton.ca (Scott Moynes) Date: Tue, 23 Oct 2001 12:33:39 -0400 Subject: [Tutor] RExec woes Message-ID: <20011023123339.H31102@marilyn> --F8dlzb82+Fcn6AgP Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable I am trying to use the rexec module and am a little confused. I wish to change the stdout within the rexec environment to be a StringIO instance so I can grab any output the users' commands generate and pass them back to them. However, I am compeletely unable to figure out how to reassign the rexec's sys.stdout. The documentation for the rexec is a little, erm, thin, and the documentation within rexec.py doesn't seem to be much help. Does anyone else have experience with rexec, or have pointers to good documentation on how to use it? Thanks, scott --=20 Copyleft (c) 2001, Scott Moynes --F8dlzb82+Fcn6AgP Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjvVm+IACgkQiPjBXy2RebCL/gCgvPxgtThtbmXXBEb+psPoF0uD QDAAoKdGtnBFZyKLt6au4FYr8CG7tevz =LIkU -----END PGP SIGNATURE----- --F8dlzb82+Fcn6AgP-- From jeff@ccvcorp.com Tue Oct 23 17:49:31 2001 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue, 23 Oct 2001 09:49:31 -0700 Subject: [Tutor] use of WxPython class, method, etc References: Message-ID: <3BD59F9B.EF1AA0F0@ccvcorp.com> > > On Tue, 23 Oct 2001 09:01:54 -0400, > dman wrote: > > On Tue, Oct 23, 2001 at 01:40:26PM +0700, Adinda-Praditya wrote: > | hi list,... > | > | i'm newbie in python world, tried to use wxpython. i read > | the manual (wxPython-docs-*.tar.gz), i think it's for C++ > | instead of python, (i don't know C++ :-( ) > > .... If not, well, ask when you have trouble and some people will > explain it. There is also a mailing list dedicated to wxPython. If you're having trouble with wxPython, I definately recommend asking on the wxPython-users mailing list--the people there are very helpful, no matter how complex or simple the question is. You should be able to find it easily through www.wxpython.org .... > > (note : all untested, but should give the general idea) > > import time > import wx #Minor note: this line should be from wxPython import wx > > > my_watch = wx.wxStopWatch() > .... Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Tue Oct 23 18:02:50 2001 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue, 23 Oct 2001 10:02:50 -0700 Subject: [Tutor] a strange(r's) question References: Message-ID: <3BD5A2BA.5A13A598@ccvcorp.com> > On Sun, 21 Oct 2001 00:31:42 +0200, > "Gregor Lingl" wrote: > > As my native language is German, I don't > know how > > Tkinter > > is pronounced correctly in English. Hm, well, since I've heard that Tcl/Tk is supposedly pronounced like "Tickle/Tick"... I've been assuming that Tkinter should be pronounced "Tick-inter" ... but maybe that's just me. :) All of my discussions regarding Python seem to take place online... > P.S. As I'm teaching Python, I have to > talk about it. Good luck with your class! Jeff Shannon Technician/Programmer Credit International From lonetwin@yahoo.com Tue Oct 23 18:11:18 2001 From: lonetwin@yahoo.com (lonetwin) Date: Tue, 23 Oct 2001 22:41:18 +0530 Subject: [Tutor] RExec woes In-Reply-To: <20011023123339.H31102@marilyn> References: <20011023123339.H31102@marilyn> Message-ID: <01102322411800.09772@mercury.worli> Hey Scott, Dunno anything about rexec expect that there is a HOWTO about it at: http://py-howto.sourceforge.net/rexec/rexec.html also from the rexec doumentation: at http://www.python.org/doc/current/lib/rexec-objects.html under 16.1.1 RExec Objects ...... ...... """Methods whose names begin with "s_" are similar to the functions beginning with "r_", but the code will be granted access to restricted versions of the standard I/O streams sys.stdin, sys.stderr, and sys.stdout.""" ...... Hope that is what you were looking for (things do slip by once in a while I guess :)) Peace Steve On Tuesday 23 October 2001 22:03, you wrote: > I am trying to use the rexec module and am a little confused. I wish > to change the stdout within the rexec environment to be a StringIO > instance so I can grab any output the users' commands generate and > pass them back to them. However, I am compeletely unable to figure out > how to reassign the rexec's sys.stdout. The documentation for the > rexec is a little, erm, thin, and the documentation within rexec.py > doesn't seem to be much help. > > Does anyone else have experience with rexec, or have pointers to good > documentation on how to use it? > > Thanks, > > scott -- ---------------------------------------------- Every oak tree started out as a couple of nuts who stood their ground. Anonymous ---------------------------------------------- From smoynes@nexus.carleton.ca Tue Oct 23 18:23:31 2001 From: smoynes@nexus.carleton.ca (Scott Moynes) Date: Tue, 23 Oct 2001 13:23:31 -0400 Subject: [Tutor] RExec woes In-Reply-To: <01102322411800.09772@mercury.worli> References: <20011023123339.H31102@marilyn> <01102322411800.09772@mercury.worli> Message-ID: <20011023132331.J31102@marilyn> --UnaWdueM1EBWVRzC Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable * lonetwin (lonetwin@yahoo.com) wrote: > Hey Scott, > Dunno anything about rexec expect that there is a HOWTO about it at: > http://py-howto.sourceforge.net/rexec/rexec.html >=20 > also from the rexec doumentation: > at http://www.python.org/doc/current/lib/rexec-objects.html > under > 16.1.1 RExec Objects > ...... > ...... >=20 > """Methods whose names begin with "s_" are similar to the functions=20 > beginning with "r_", but the code will be granted access to restricted=20 > versions of the standard I/O streams sys.stdin, sys.stderr, and sys.stdou= t.""" Fortunately, I have read both those documents in full, and they are helpful for simple things like adding variables, and changing permissions, but unfortunately they do not have any hints on how do save the results of the users' command.=20 As a quick example, here's approximately what I'm trying to accomplish: >>> r=3Drexec.RExec() >>> m=3Dr.add_module('sys') >>> s=3DStringIO.StringIO() >>> m.__dict__['stdin']=3Ds >>> r.r_exec('print "something"') something >>> s.getvalue() '' >>>=20 However, in a perfect world where I knew what I was doing, s would hold the result of 'print "something"' and could pass this string back to the user. The s_* functions don't seem to act any differently. scott --=20 Copyleft (c) 2001, Scott Moynes --UnaWdueM1EBWVRzC Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjvVp5MACgkQiPjBXy2RebA1ZgCggJTbEWLrFtbookzGJ8gDSKXb 5w8An2p0CmEgooMy3QQNxG4rKjchrZ5j =ERb6 -----END PGP SIGNATURE----- --UnaWdueM1EBWVRzC-- From scarblac@pino.selwerd.nl Tue Oct 23 18:42:26 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Tue, 23 Oct 2001 19:42:26 +0200 Subject: [Tutor] RExec woes In-Reply-To: <20011023132331.J31102@marilyn>; from smoynes@nexus.carleton.ca on Tue, Oct 23, 2001 at 01:23:31PM -0400 References: <20011023123339.H31102@marilyn> <01102322411800.09772@mercury.worli> <20011023132331.J31102@marilyn> Message-ID: <20011023194226.A15624@pino.selwerd.nl> On 0, Scott Moynes wrote: > Fortunately, I have read both those documents in full, and they are > helpful for simple things like adding variables, and changing > permissions, but unfortunately they do not have any hints on how do > save the results of the users' command. > As a quick example, here's approximately what I'm trying to > accomplish: > > >>> r=rexec.RExec() > >>> m=r.add_module('sys') > >>> s=StringIO.StringIO() > >>> m.__dict__['stdin']=s > >>> r.r_exec('print "something"') > something > >>> s.getvalue() > '' > >>> You have a silly error here; you change stdin, but print prints to stdout. Unfortunately, that doesn't solve the problem :-(. It does work if you change stdout in the normal program, and then start the rexec: import sys, rexec, StringIO s = StringIO.StringIO() try: # try...finally makes sure that stdout is always reset correctly sys.stdout = s r.r_exec('print "something"') finally: sys.stdout = sys.__stdout__ print "s:", s.getvalue(), This worked for me. Hope you can use this way to do it. Possibly add more intelligence around StringIO() if you don't always need to redirect the output inside rexec. I don't know if this has security implications (rexec is a security thing, after all). -- Remco Gerlich From smoynes@nexus.carleton.ca Tue Oct 23 19:06:36 2001 From: smoynes@nexus.carleton.ca (Scott Moynes) Date: Tue, 23 Oct 2001 14:06:36 -0400 Subject: [Tutor] RExec woes In-Reply-To: <20011023194226.A15624@pino.selwerd.nl> References: <20011023123339.H31102@marilyn> <01102322411800.09772@mercury.worli> <20011023132331.J31102@marilyn> <20011023194226.A15624@pino.selwerd.nl> Message-ID: <20011023140636.K31102@marilyn> --4f28nU6agdXSinmL Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable * Remco Gerlich (scarblac@pino.selwerd.nl) wrote: > You have a silly error here; you change stdin, but print prints to stdout. >=20 > Unfortunately, that doesn't solve the problem :-(. >=20 > It does work if you change stdout in the normal program, and then start t= he > rexec: Hrmm, I never thought of that. Not the most elegant solution, but I suppose it will have to do for now. (Geez. I sound like I am writing Perl here. :D ) Thank you very much, scott --=20 Copyleft (c) 2001, Scott Moynes --4f28nU6agdXSinmL Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjvVsawACgkQiPjBXy2RebA0PQCfSyUrufSbTcMPK71DR2QKhUUV +TUAnjNW9BVbw81O8ih1M2AJGrMyWO// =S8H9 -----END PGP SIGNATURE----- --4f28nU6agdXSinmL-- From david.jay.jackson@wcox.com Tue Oct 23 20:18:05 2001 From: david.jay.jackson@wcox.com (Jackson) Date: Tue, 23 Oct 2001 13:18:05 -0600 Subject: [Tutor] Questions about shelve Message-ID: <200110231318.AA184484152@wcox.com> Objective (Please see script below): Create simple server outage tracking db. While MySQL would be easer to use, it's not as much fun *grin* Data layout: Each record consist of; hostname,date,problem,resolution with hostname and date beging key fields, and problem/resolution being multi-line text field. What's missing: 1. Need to be able to enter more than one outage per server, did I read someplace that you can set Btree to allow dup keys? 2. Change "end_of_field" char to Ctrl+a to allow multi line imput for problem and resolution fields. Thanks for you time. David Jackson ------------- Script ----------------------- #!/usr/bin/python import shelve # people = shelve.open("/tmp/btree.db") host=raw_input("Enter Hostname: ") date=raw_input("Date of Outage: ") problem=raw_input("Problem Descrption: ") resolution=raw_input("Problem Resolution: ") people[host]=[date,problem,resolution] people.close() From ak@silmarill.org Tue Oct 23 20:29:21 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Tue, 23 Oct 2001 15:29:21 -0400 Subject: [Tutor] Questions about shelve In-Reply-To: <200110231318.AA184484152@wcox.com> References: <200110231318.AA184484152@wcox.com> Message-ID: <20011023152921.A13550@sill.silmarill.org> On Tue, Oct 23, 2001 at 01:18:05PM -0600, Jackson wrote: > Objective (Please see script below): > Create simple server outage tracking db. While MySQL > would be easer to use, it's not as much fun *grin* > > Data layout: > Each record consist of; hostname,date,problem,resolution with > hostname and date beging key fields, and problem/resolution being multi-line text field. > > What's missing: > 1. Need to be able to enter more than one outage per server, did I read someplace that you can set Btree to allow dup keys? Why multiple keys? Just make the value a list of outages. > > 2. Change "end_of_field" char to Ctrl+a to allow multi line imput for problem and resolution fields. Look into curses module (fairly complex) or Tkinter. > > Thanks for you time. > David Jackson > > > ------------- Script ----------------------- > > #!/usr/bin/python > import shelve > # > people = shelve.open("/tmp/btree.db") > host=raw_input("Enter Hostname: ") > date=raw_input("Date of Outage: ") problem=raw_input("Problem Descrption: ") > resolution=raw_input("Problem Resolution: ") > people[host]=[date,problem,resolution] > people.close() > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From kalle@gnupung.net Tue Oct 23 21:21:06 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Tue, 23 Oct 2001 22:21:06 +0200 Subject: [Tutor] Questions about shelve In-Reply-To: <200110231318.AA184484152@wcox.com> References: <200110231318.AA184484152@wcox.com> Message-ID: <20011023222106.B8097@sandra.lysator.liu.se> [Jackson] > 2. Change "end_of_field" char to Ctrl+a to allow multi line imput for > problem and resolution fields. Try something like this function: def get_input(prompt): lines = [] while 1: s = raw_input(prompt) if s == ".": break lines.append(s) return "\n".join(lines) End input with a . on a line by itself, like Prompt: Hello! Prompt: Prompt: Fish. Prompt: . Peace, Kalle -- [ Thought control, brought to you by the WIPO! ] [ http://anti-dmca.org/ http://eurorights.org/ ] From dyoo@hkn.eecs.berkeley.edu Wed Oct 24 06:58:27 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 23 Oct 2001 22:58:27 -0700 (PDT) Subject: [Tutor] Learning about other languages by using Python [Scheme!] Message-ID: This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. Send mail to mime@docserver.cac.washington.edu for more info. --545280650-737955794-1003903107=:15261 Content-Type: TEXT/PLAIN; charset=US-ASCII [Skip this message if you're just beginning to learn Python; this post refers to another language called Scheme, so it might be confusing.] Hi everyone, I'm thinking of writing a silly Scheme interpreter in Python; hopefully I'll be able to get it done before I forget. *grin* Scheme is one of the "simple" languages that beginning computer science students often play with. It has almost no syntax, which makes it relatively easy to write a parser for it. Almost all of Scheme is based on processing lists, so Scheme optimizes its syntax toward list building. For example, in Scheme, (one two (three) 4) is equivalent to Python's: ['one', 'two', ['three'], 4] Just in case I get hit by a bus, I'll send off a bit that already (sorta) works to Useless Python. ### dyoo@einfall:~/pyscheme$ python schemeparser.py Type 'quit' to exit this test. [SchemeParser] >>> (define (square x) (* x x)) ['define', ['square', 'x'], ['*', 'x', 'x']] [SchemeParser] >>> (1 2 3 4 (5 6 (7 8 (9))) 10) [1, 2, 3, 4, [5, 6, [7, 8, [9]]], 10] [SchemeParser] >>> this shouldn't work Uh oh! While trying to eat None: got token ('symbol', 'shouldn') instead. [SchemeParser] >>> ''''muhahaha ['quote', ['quote', ['quote', ['quote', 'muhahaha']]]] ### Hope this helps! --545280650-737955794-1003903107=:15261 Content-Type: TEXT/PLAIN; charset=US-ASCII; name="prompt.py" Content-Transfer-Encoding: BASE64 Content-ID: Content-Description: Content-Disposition: attachment; filename="prompt.py" IiIiQSBzbWFsbCBwcm9tcHRpbmcgY2xhc3MuDQoNCkRhbm55IFlvbyAoZHlv b0Boa24uZWVjcy5iZXJrZWxleS5lZHUpDQoNClRoaXMgaGFzbid0IGJlZW4g dG9vIGRvY3VtZW50ZWQgeWV0LiAgVGhlcmUncyBzb21lIHNhbXBsZSB1c2Vz IG9uDQp0aGUgYm90dG9tIHdpdGggdGhlIHRlc3QoKSBmdW5jdGlvbiBiZWxv dy4NCiIiIg0KDQoNCiMjIEZpcnN0LCBsZXQncyBzZWUgaWYgd2UgY2FuIGxv YWQgdXAgcmVhZGxpbmUgYW5kIG1ha2UgcmF3X2lucHV0KCkNCiMjIG5pY2Ug dG8gd29yayB3aXRoLg0KdHJ5Og0KICAgIGltcG9ydCByZWFkbGluZQ0KZXhj ZXB0IEltcG9ydEVycm9yOiBwYXNzDQoNCmltcG9ydCBzeXMNCmltcG9ydCBw cHJpbnQNCg0KY2xhc3MgUHJvbXB0Og0KICAgIGRlZiBfX2luaXRfXyhzZWxm LCBuYW1lLCBxdWl0X3N0ciA9ICdxdWl0JywgcXVpdF9jbWQ9c3lzLmV4aXQs DQogICAgICAgICAgICAgICAgIGNhbGxiYWNrPU5vbmUpOg0KICAgICAgICBz ZWxmLm5hbWUgPSBuYW1lDQogICAgICAgIHNlbGYucXVpdF9zdHIgPSBxdWl0 X3N0cg0KICAgICAgICBzZWxmLnF1aXRfY21kID0gcXVpdF9jbWQNCiAgICAg ICAgc2VsZi5jYWxsYmFjayA9IGNhbGxiYWNrDQogICAgICAgIA0KICAgIGRl ZiBwcm9tcHRMb29wKHNlbGYpOg0KICAgICAgICB3aGlsZSAxOg0KICAgICAg ICAgICAgdHJ5Og0KICAgICAgICAgICAgICAgIHMgPSByYXdfaW5wdXQoJ1sl c10gPj4+ICcgJSBzZWxmLm5hbWUpDQogICAgICAgICAgICAgICAgaWYgcyA9 PSBzZWxmLnF1aXRfc3RyOg0KICAgICAgICAgICAgICAgICAgICByYWlzZSBF T0ZFcnJvcg0KICAgICAgICAgICAgICAgIGVsaWYgcyBhbmQgc2VsZi5jYWxs YmFjazoNCiAgICAgICAgICAgICAgICAgICAgcmVzdWx0ID0gc2VsZi5jYWxs YmFjayhzKQ0KICAgICAgICAgICAgICAgICAgICBpZiByZXN1bHQgIT0gTm9u ZToNCiAgICAgICAgICAgICAgICAgICAgICAgIHBwcmludC5wcHJpbnQocmVz dWx0KQ0KICAgICAgICAgICAgZXhjZXB0IChFT0ZFcnJvciwgS2V5Ym9hcmRJ bnRlcnJ1cHQpOg0KICAgICAgICAgICAgICAgIHByaW50DQogICAgICAgICAg ICAgICAgcmV0dXJuIHNlbGYucXVpdF9jbWQNCg0KDQoNCiMjIyMjIyMjIyMj IyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMj IyMjIyMjIyMjIyMjIyMNCg0KIyMgTm90ZTogSSBzaG91bGQgcHJvYmFibHkg dXNlIHRoZSB1bml0IHRlc3RpbmcgbW9kdWxlcy4NCmRlZiB0ZXN0KCk6DQog ICAgZGVmIGVjaG9DYWxsYmFjayhzKToNCiAgICAgICAgcHJpbnQgcw0KICAg IHAgPSBQcm9tcHQoJ3Rlc3QnLCBjYWxsYmFjaz1lY2hvQ2FsbGJhY2spDQog ICAgcC5wcm9tcHRMb29wKCkNCg0KDQppZiBfX25hbWVfXyA9PSAnX19tYWlu X18nOg0KICAgIHRlc3QoKQ0K --545280650-737955794-1003903107=:15261 Content-Type: TEXT/PLAIN; charset=US-ASCII; name="schemeparser.py" Content-Transfer-Encoding: BASE64 Content-ID: Content-Description: Content-Disposition: attachment; filename="schemeparser.py" aW1wb3J0IHJlDQoNCiIiIkEgc21hbGwgc2NoZW1lIHBhcnNlci4NCg0KRGFu bnkgWW9vIChkeW9vQGhrbi5lZWNzLmJlcmtlbGV5LmVkdSkNCk9jdG9iZXIg MjMsIDIwMDEuDQoNCkEgcmVjdXJzaXZlIGRlc2NlbnQgcGFyc2VyLCBxdWlj a2x5IGNvb2tlZCB1cC4gIE5vIHNwZWNpYWwgbGlicmFyaWVzDQpuZWNlc3Nh cnkgZXhjZXB0IGZvciB0aGUgJ3JlJyByZWd1bGFyIGV4cHJlc3Npb24gbGli cmFyeS4NCg0KVGhpcyBwYXJzZXIgbWlnaHQgYmUgdXNlZnVsIGlmIHdlIHdh bnRlZCB0byBncmFiIGluZm9ybWF0aW9uIGZyb20gdGhlDQp1c2VyIHVzaW5n IFNjaGVtZWlzaCBsaXN0cy4gIEl0IG1pZ2h0IGFsc28gYmUgbmljZSBpZiBv bmUgaXMgcGxhbm5pbmcNCnRvIHdyaXRlIGEgU2NoZW1lIGludGVycHJldGVy IGluIFB5dGhvbi4NCg0KVGhlIG1haW4gZnVuY3Rpb25zIHRvIHVzZSBpbiB0 aGlzIG1vZHVsZSBhcmUNCg0KICAgIHRva2VuaXplKCk6IG1ha2VzIGEgbGlz dCBvZiB0b2tlbnMgb3V0IG9mIGEgc3RyaW5nDQogICAgcGFyc2VFeHByZXNz aW9uKCk6IHR1cm5zIHRob3NlIHRva2VucyBpbnRvIGEgcGFyc2VkIGV4cHJl c3Npb24NCg0KQW4gZXh0cmEgc3RyaWN0ICdwYXJzZVNpbmdsZUV4cHJlc3Np b24oKScgbWFrZXMgc3VyZSB0aGF0IGl0IHVzZXMgdXANCmFsbCB0aGUgdG9r ZW5zIHRoYXQgaXQgaGFzIGJlZW4gZ2l2ZW4uDQoNCklmIGFueXRoaW5nIGJh ZCBoYXBwZW5zIGR1cmluZyB0aGUgcGFyc2luZywgd2UnbGwgcmFpc2UgYSBQ YXJzZXJFcnJvci4NCiIiIg0KDQoNCg0KIiIiVGhlIEVuZCBPZiBGaWxlIHRv a2VuIGlzIGEgc2VudGluYWwgdGhhdCB0ZXJtaW5hdGVzIGEgbGlzdCBvZiB0 b2tlbnMuIiIiDQpFT0ZfVE9LRU4gPSAoTm9uZSwgTm9uZSkNCg0KDQoiIiJI ZXJlIGFyZSB0aGUgcGF0dGVybnMgd2UgcGF5IGF0dGVudGlvbiB3aGVuIGJy ZWFraW5nIGRvd24gYSBzdHJpbmcNCmludG8gdG9rZW5zLiIiIg0KUEFUVEVS TlMgPSBbICgnd2hpdGVzcGFjZScsIHJlLmNvbXBpbGUocidccysnKSksDQog ICAgICAgICAgICAgKCcoJywgcmUuY29tcGlsZShyJ1woJykpLA0KICAgICAg ICAgICAgICgnKScsIHJlLmNvbXBpbGUocidcKScpKSwNCiAgICAgICAgICAg ICAoJ251bWJlcicsIHJlLmNvbXBpbGUocicnJ1xkK1wuXGQrDQogICAgICAg ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHxcZCtcLg0KICAgICAg ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB8XC5cZCsNCiAgICAg ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgfFxkKycnJywNCiAg ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgcmUuVkVSQk9TRSkp LA0KICAgICAgICAgICAgICgnc3ltYm9sJywgcmUuY29tcGlsZShyJycnW2Et ekEtWlwrXD9cIVxAXCNcJFwlXF5cJlwqXC1cL1wuXQ0KICAgICAgICAgICAg ICAgICAgICAgICAgICAgICAgICAgICAgICAgW1x3XCtcP1whXEBcI1wkXCVc XlwmXCpcLVwvXC5dKicnJywNCiAgICAgICAgICAgICAgICAgICAgICAgICAg ICAgICAgICAgcmUuVkVSQk9TRSkpLA0KICAgICAgICAgICAgICgnXCcnLCBy ZS5jb21waWxlKHInXCcnKSksDQogICAgICAgICAgICAgXQ0KDQoNCmRlZiB0 b2tlbml6ZShzKToNCiAgICAiIiJHaXZlbiBhIHN0cmluZyAncycsIHJldHVy biBhIGxpc3Qgb2YgaXRzIHRva2Vucy4NCiAgICBBIHRva2VuIGNhbiBiZSBv bmUgb2YgdGhlIGZvbGxvd2luZyB0eXBlczoNCg0KICAgICAgICBbIigiLCAi KSIsIE5VTUJFUiwgU1lNQk9MLCAiXCciXQ0KICAgICAgICANCiAgICBhbmQg ZWFjaCB0b2tlbiBpcyBhIDItdHVwbGU6ICh0eXBlLCBjb250ZW50KS4NCiAg ICAiIiINCiAgICB0b2tlbnMgPSBbXQ0KICAgIHdoaWxlIDE6DQogICAgICAg IHNob3VsZF9jb250aW51ZSA9IDANCiAgICAgICAgZm9yIHR5cGUsIHJlZ2V4 IGluIFBBVFRFUk5TOg0KICAgICAgICAgICAgbWF0Y2hfb2JqID0gcmVnZXgu bWF0Y2gocykNCiAgICAgICAgICAgIGlmIG1hdGNoX29iajoNCiAgICAgICAg ICAgICAgICBzaG91bGRfY29udGludWUgPSAxDQogICAgICAgICAgICAgICAg dG9rZW5zLmFwcGVuZCggKHR5cGUsIG1hdGNoX29iai5ncm91cCgwKSkgKQ0K ICAgICAgICAgICAgICAgIHMgPSBzW21hdGNoX29iai5zcGFuKClbMV0gOl0N CiAgICAgICAgaWYgc2hvdWxkX2NvbnRpbnVlID09IDA6DQogICAgICAgICAg ICBicmVhaw0KICAgIHRva2Vucy5hcHBlbmQoRU9GX1RPS0VOKQ0KICAgIHJl dHVybiBmaWx0ZXIobGFtYmRhIHg6IHhbMF0gIT0gJ3doaXRlc3BhY2UnLCB0 b2tlbnMpDQoNCg0KIiIiV2l0aCB0aGUgbGV4ZXIgZG9uZSwgbm93IGxldCdz IGRpcmVjdCBvdXIgYXR0ZW50aW9uIHRvIHRoZSBwYXJzZXIuIiIiDQojIyMj IyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMj IyMjIyMjIyMjIyMjIyMjIyMjIyMjDQoNCmNsYXNzIFBhcnNlckVycm9yKEV4 Y2VwdGlvbik6DQogICAgIiIiT3VyIHBlcnNvbmFsaXplZCBleGNlcHRpb24g Y2xhc3MuIiIiDQogICAgcGFzcw0KDQoNCmRlZiBwZWVrKHRva2Vucyk6DQog ICAgIiIiVGFrZSBhIHF1aWNrIGdsYW5jZSBhdCB0aGUgZmlyc3QgdG9rZW4g aW4gb3VyIHRva2VucyBsaXN0LiIiIg0KICAgIGlmIGxlbih0b2tlbnMpID09 IDA6DQogICAgICAgIHJhaXNlIFBhcnNlckVycm9yLCAiV2hpbGUgcGVla2lu ZzogcmFuIG91dCBvZiB0b2tlbnMuIg0KICAgIHJldHVybiB0b2tlbnNbMF0N Cg0KDQpkZWYgZWF0KHRva2VucywgdHlwZSk6DQogICAgIiIiRGlnZXN0IHRo ZSBmaXJzdCB0b2tlbiBpbiBvdXIgdG9rZW5zIGxpc3QsIG1ha2luZyBzdXJl IHRoYXQgd2UncmUNCiAgICBiaXRpbmcgb24gdGhlIHJpZ2h0IHR5cGUgb2Yg dGhpbmcuIiIiDQogICAgaWYgbGVuKHRva2VucykgPT0gMDoNCiAgICAgICAg cmFpc2UgUGFyc2VyRXJyb3IsICJXaGlsZSB0cnlpbmcgdG8gZWF0ICVzOiBy YW4gb3V0IG9mIHRva2Vucy4iICUgXA0KICAgICAgICAgICAgICAocmVwcih0 eXBlKSwpDQogICAgaWYgdG9rZW5zWzBdWzBdICE9IHR5cGU6DQogICAgICAg IHJhaXNlIFBhcnNlckVycm9yLCAiV2hpbGUgdHJ5aW5nIHRvIGVhdCAlczog Z290IHRva2VuICVzIGluc3RlYWQuIiAlIFwNCiAgICAgICAgICAgICAgICAg ICAgICAgICAgICAocmVwcih0eXBlKSwgcmVwcih0b2tlbnNbMF0pKQ0KICAg IHJldHVybiB0b2tlbnMucG9wKDApDQoNCiMjIyMjIyMjIyMjIyMjIyMjIyMj IyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMj IyMjIyMNCiIiIkJlbG93IGlzIGEgYnVuY2ggb2YgcGFyc2luZyBmdW5jdGlv bnMuICBXZSdsbCB1c2UgYSByZWN1cnNpdmUNCmRlc2NlbnQgcGFyc2luZyB0 ZWNobmlxdWUsIHNpbmNlIFNjaGVtZSBpcyBzbyB3ZWxsIHN1aXRlZCBmb3Ig aXQuIiIiDQoNCg0KZGVmIHBhcnNlU2luZ2xlRXhwcmVzc2lvbih0b2tlbnMp Og0KICAgICIiIlJldHVybnMgYSBzaW5nbGUgRXhwcmVzc2lvbiwgZ2l2ZW4g YSBzZXF1ZW5jZSBvZiB0b2tlbnMuDQogICAgUmFpc2VzIGEgUGFyc2VyRXhj ZXB0aW9uIGlmIG91ciB0b2tlbnMgaGF2ZW4ndCBiZWVuIGV4aGF1c3RlZC4i IiINCiAgICBleHByZXNzaW9uID0gcGFyc2VFeHByZXNzaW9uKHRva2VucykN CiAgICBlYXQodG9rZW5zLCBOb25lKSAgIyMgRWF0IHRoZSBFT0YgdG9rZW4N CiAgICByZXR1cm4gZXhwcmVzc2lvbg0KDQoNCmRlZiBwYXJzZUV4cHJlc3Np b24odG9rZW5zKToNCiAgICAiIiJSZXR1cm5zIGFuIEV4cHJlc3Npb24sIGdp dmVuIGEgc2VxdWVuY2Ugb2YgdG9rZW5zLg0KICAgIEFuIGV4cHJlc3Npb24g aXMgbWFkZSB1cCBvZiBvbmUgb2YgdGhlIGZvbGxvd2luZyB0aGluZ3M6DQog ICAgICAgIG8gIEEgcXVvdGVkIGV4cHJlc3Npb24NCiAgICAgICAgbyAgQW4g YXRvbSAobGlrZSBhIG51bWJlciBvciBzeW1ib2wpDQogICAgICAgIG8gIEEg bGlzdC4NCiAgICBUaGlzIHByb2NlZHVyZSB0cmllcyB0byB0YWtlIGNhcmUg b2YgYWxsIHRoZXNlIHBvdGVudGlhbHMuIiIiDQogICAgbG9va19haGVhZF90 eXBlID0gcGVlayh0b2tlbnMpWzBdDQogICAgaWYgbG9va19haGVhZF90eXBl ID09ICdcJyc6DQogICAgICAgIGVhdCh0b2tlbnMsICdcJycpDQogICAgICAg IHJldHVybiBbJ3F1b3RlJywgcGFyc2VFeHByZXNzaW9uKHRva2VucyldDQog ICAgZWxpZiBsb29rX2FoZWFkX3R5cGUgPT0gJygnOg0KICAgICAgICByZXR1 cm4gcGFyc2VMaXN0KHRva2VucykNCiAgICBlbGlmIGxvb2tfYWhlYWRfdHlw ZSBpbiAoJ251bWJlcicsICdzeW1ib2wnKToNCiAgICAgICAgcmV0dXJuIHBh cnNlQXRvbSh0b2tlbnMpDQoNCg0KZGVmIHBhcnNlQXRvbSh0b2tlbnMpOg0K ICAgICIiIlJldHVybnMgYW4gQXRvbSwgZ2l2ZW4gYSBzZXF1ZW5jZSBvZiB0 b2tlbnMuDQogICAgQW4gYXRvbSBpcyBlaXRoZXIgYSBudW1iZXIgb3IgYSBz eW1ib2wuIiIiDQogICAgaWYgcGVlayh0b2tlbnMpWzBdID09ICdudW1iZXIn Og0KICAgICAgICByZXR1cm4gZXZhbChlYXQodG9rZW5zLCAnbnVtYmVyJylb MV0sIHt9KSAgIyMgZXZhbCgpIHNob3VsZCBiZSBvaw0KICAgICAgICAgICAg ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIyMgc2lu Y2UgdGhlIGlucHV0IGlzDQogICAgICAgICAgICAgICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgICAgICAgICAjIyBzYW50aXRpemVkLg0KICAgIGVs c2U6DQogICAgICAgIHJldHVybiBlYXQodG9rZW5zLCAnc3ltYm9sJylbMV0N Cg0KDQpkZWYgcGFyc2VMaXN0KHRva2Vucyk6DQogICAgIiIiUmV0dXJucyBh IExpc3QgdGhhdCBwb3NzaWJseSBjb250YWlucyBhIGJ1bmNoIG9mIEV4cHJl c3Npb25zLiIiIg0KICAgIGVhdCh0b2tlbnMsICcoJykNCiAgICBwYXJzZWRf ZWxlbWVudHMgPSBbXQ0KICAgIHdoaWxlIDE6DQogICAgICAgIGxvb2tfYWhl YWRfdHlwZSA9IHBlZWsodG9rZW5zKVswXQ0KICAgICAgICBpZiBsb29rX2Fo ZWFkX3R5cGUgaW4gKCdcJycsICcoJywgJ251bWJlcicsICdzeW1ib2wnKToN CiAgICAgICAgICAgIHBhcnNlZF9lbGVtZW50cy5hcHBlbmQocGFyc2VFeHBy ZXNzaW9uKHRva2VucykpDQogICAgICAgIGVsc2U6IGJyZWFrDQogICAgZWF0 KHRva2VucywgJyknKQ0KICAgIHJldHVybiBwYXJzZWRfZWxlbWVudHMNCg0K DQoNCiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMj IyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMNCg0KaWYgX19uYW1lX18g PT0gJ19fbWFpbl9fJzoNCiAgICAiIiJBIGxpdHRsZSB0ZXN0IGhhcm5lc3Mg Zm9yIHRoZSBwYXJzZXIuIiIiDQogICAgZGVmIF9jYWxsYmFjayhzKToNCiAg ICAgICAgdHJ5Og0KICAgICAgICAgICAgcHJpbnQgcGFyc2VTaW5nbGVFeHBy ZXNzaW9uKHRva2VuaXplKHMpKQ0KICAgICAgICBleGNlcHQgUGFyc2VyRXJy b3IsIHM6DQogICAgICAgICAgICBwcmludCAiVWggb2ghIiwgcw0KICAgIGZy b20gcHJvbXB0IGltcG9ydCBQcm9tcHQNCiAgICBwID0gUHJvbXB0KG5hbWU9 IlNjaGVtZVBhcnNlciIsIGNhbGxiYWNrPV9jYWxsYmFjaykNCiAgICBwcmlu dCAiVHlwZSAncXVpdCcgdG8gZXhpdCB0aGlzIHRlc3QuIg0KICAgIHAucHJv bXB0TG9vcCgpDQo= --545280650-737955794-1003903107=:15261-- From shalehperry@home.com Wed Oct 24 09:17:16 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Wed, 24 Oct 2001 01:17:16 -0700 (PDT) Subject: [Tutor] Learning about other languages by using Python [S In-Reply-To: Message-ID: Care to point out a really good Scheme language reference online? I should write one of those myself. I missed out on all of the fun reasons people took CS. From scarblac@pino.selwerd.nl Wed Oct 24 09:26:15 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 24 Oct 2001 10:26:15 +0200 Subject: [Tutor] Learning about other languages by using Python [S In-Reply-To: ; from shalehperry@home.com on Wed, Oct 24, 2001 at 01:17:16AM -0700 References: Message-ID: <20011024102615.A16662@pino.selwerd.nl> On 0, Sean 'Shaleh' Perry wrote: > Care to point out a really good Scheme language reference online? I should > write one of those myself. I missed out on all of the fun reasons people took > CS. No, but if you want to learn the basics, try the Java applet text adventure at http://www.eblong.com/zarf/zplet/lists.html . It's only two rooms, and you can find 'A Simple Programmer's Reference to Scheme' in it :-). And do the puzzles. And I *still* can't do the last one, for which you have to wrap your brain around recursion in several new and twisted ways. I don't think I can say I grok Scheme before I crack that one, but no luck so far. Hmm, that said, I seem to remember you knew Scheme already but was writing an interpreter (that previous email was by you? i have no memory in the morning) but it's still a cool link for everyone else - solve a text adventure and learn a neat language :-) -- Remco Gerlich From pemrograman@telkom.net Wed Oct 24 21:56:40 2001 From: pemrograman@telkom.net (Adinda Praditya) Date: Thu, 25 Oct 2001 03:56:40 +0700 Subject: [Tutor] use of WxPython class, method, etc References: <4.2.0.58.20011012195907.00c55220@pop3.norton.antivirus> <20011023090154.A14184@harmony.cs.rit.edu> Message-ID: <019e01c15cce$8fd565b0$0101a8c0@baitullah> ----- Original Message ----- From: "dman" To: Sent: Tuesday, October 23, 2001 8:01 PM Subject: Re: [Tutor] use of WxPython class, method, etc > import time > import wx > > my_watch = wx.wxStopWatch() > time.sleep( 2 ) > print my_watch.Time() > my_watch.Pause() > time.sleep( 2 ) > print my_watch.Time() > my_watch.Resume() > time.sleep( 2 ) > print my_watch.Time() > > I've tried something like this, but still have an error. I restarted over then. here's another story about my problem. From manual : === There are two different ways to use this class: You may derive a new class from wxTimer and override the Notify member to perform the required action. Or you may redirect the notifications to any wxEvtHandler derived object by using the non default constructor or SetOwner. Then use EVT_TIMER macro to connect it to the event handler which will receive wxTimerEvent notifications. In any case, you must start the timer with Start after constructing it before it actually starts sending notifications. It can be stopped later with Stop. wxTimer() Default constructor. If you use it to construct the object and don't call SetOwner later, you must override Notify method to process the notifications. wxTimer(wxEvtHandler *owner, int id = -1) Creates a timer and associates it with owner. Please see SetOwner for the description of parameters. === My question is how can i override Notify method? How can i use wxTimer? Again, from manual, === wxTimer::Notify void Notify() This member should be overridden by the user if the default constructor was used and SetOwner wasn't called. Perform whatever action which is to be taken periodically here. === I tried several way, wxTimer(Notify) ==> NameError: There is no variable named 'Notify' wxtimer() ==> AttributeError: 'wxTimer' instance has no attribute 'Notify' wxTimer.Notify() ==> AttributeError: Notify wxTimerNotify() ==> NameError: There is no variable named 'wxTimerNotify' Did i miss something? I think the manual doesn't give me a clear definition and syntax or i'm a stupid person! I still don't get it. Does anyone has a better explanation to understand these stuff (how to use, work with class, method, object) Please help me. thank you, Adinda Praditya From lonetwin Wed Oct 24 13:30:27 2001 From: lonetwin (lonetwin) Date: Wed, 24 Oct 2001 18:00:27 +0530 (IST) Subject: [Tutor] Attachment to a mail message Message-ID: Hi all, I have a lil' question, how does one send a mail alongwith an attachment using python ?? I already know that one can do a import smtplib conn = smtplib.SMTP(Server) conn.sendmail(From, To_addr, Msg) to send Msg to To_addr, thru' Server.... ....I'd like to learn how to add an attachment (MIME encoded ??) to this Msg, so that I can send mail with attachments confirming to mail standards on the net. I had a look at three mime related modules mimetools, MimeWriter and mimify from the std. lib, but since I don't know anything about MIME (the what...the where ..the why ...the how) I could not decide on even how to begin playing around with these...I'm hoping somebody could give me a quick crash course on this or at least point me to some nice resource (just something that provides a simple explaination....where a quick read-thru' will explain what happens when we send/recieve a mail with attachments) Peace Steve -- ---------------------------------------------- Every oak tree started out as a couple of nuts who stood their ground. Anonymous ---------------------------------------------- From arcege@speakeasy.net Wed Oct 24 14:17:22 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Wed, 24 Oct 2001 09:17:22 -0400 Subject: [Tutor] Attachment to a mail message In-Reply-To: ; from lonetwin@yahoo.com on Wed, Oct 24, 2001 at 06:00:27PM +0530 References: Message-ID: <20011024091722.A990@speakeasy.net> On Wed, Oct 24, 2001 at 06:00:27PM +0530, lonetwin wrote: > Hi all, > I have a lil' question, how does one send a mail alongwith an > attachment using python ?? I already know that one can do a > > import smtplib > conn = smtplib.SMTP(Server) > conn.sendmail(From, To_addr, Msg) > > to send Msg to To_addr, thru' Server.... > ....I'd like to learn how to add an attachment (MIME encoded ??) to this Msg, > so that I can send mail with attachments confirming to mail standards on the net. Hi there, The existing MIME modules are not all that useful. There are two additional third party modules that do the job for you: mimecntl (at http://starship.python.net/crew/arcege/modules/mimecntl.html) and mimelib (at http://mimelib.sourceforge.net/). With both, you can create MIME documents that can be sent as-is through smtplib. For example: # MIME_document is the base class, MIME_recoder_f is specialized to # encode large data to an external temporary file from mimecntl import MIME_document, MIME_recoder_f, MIMEField # make some text to go with the attachment mail_body = MIME_document("""\ Hey there, this is the picture from July 4th that you wished to see. """) # now load in the picture; basic data objects are treated as files # so we read binary data blocks and write them to the MIME object jpeg_file = open('fireworks.jpg', 'rb') # we create a new encodable object, with a "content-type" of a JPEG # image, and the name of the file attachment = MIME_recoder_f( type=MIMEField('Content-Type', 'image/jpeg', name='fireworks.jpg') ) jpeg_length = 0 block = jpeg_file.read(1024) while block: jpeg_length = jpeg_length + len(block) attachment.write(block) block = jpeg_file.read(1024) # but we want to encode in base64 encoded_attachment = attachment.encode('base64') # the system does not add fields itself, it only does what you want encoded_attachment['Content-Length'] = jpeg_length # now combine them together into a multipart document message = MIME_document( (mail_body, attachment), From=From, To=To_addr, Subject="Fourth of July Fireworks" ) # send the document through your smtplib.SMTP object conn.sendmail( message['from'], # the "From" field of the message tuple(message['to']), # multiple items in field (sendmail wants a tuple) str(message) # the message as a complete string document ) I hope this helps. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From shalehperry@home.com Wed Oct 24 16:14:46 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Wed, 24 Oct 2001 08:14:46 -0700 (PDT) Subject: [Tutor] Learning about other languages by using Python [S In-Reply-To: <20011024102615.A16662@pino.selwerd.nl> Message-ID: > > No, but if you want to learn the basics, try the Java applet text adventure > at > http://www.eblong.com/zarf/zplet/lists.html . It's only two rooms, and you > can find 'A Simple Programmer's Reference to Scheme' in it :-). And do the > puzzles. > oooo, great link. Thanks. > > Hmm, that said, I seem to remember you knew Scheme already but was writing > an interpreter (that previous email was by you? i have no memory in the > morning) but it's still a cool link for everyone else - solve a text > adventure and learn a neat language :-) > no, that was Danny. I was asking Danny for pointers to more info (-: From lonetwin@yahoo.com Wed Oct 24 16:46:08 2001 From: lonetwin@yahoo.com (lonetwin) Date: Wed, 24 Oct 2001 21:16:08 +0530 Subject: [Tutor] Attachment to a mail message In-Reply-To: <20011024091722.A990@speakeasy.net> References: <20011024091722.A990@speakeasy.net> Message-ID: <01102421160800.04525@mercury.worli> Hey Arcege Thanx a lot for those links ...I'll just go ahead and use one of them ...although I'll still be waiting for someone to give me a idea of doing this with the std lib modules...just so that I know. Peace Steve On Wednesday 24 October 2001 18:47, you wrote: > On Wed, Oct 24, 2001 at 06:00:27PM +0530, lonetwin wrote: > > Hi all, > > I have a lil' question, how does one send a mail alongwith an > > attachment using python ?? I already know that one can do a > > > > import smtplib > > conn = smtplib.SMTP(Server) > > conn.sendmail(From, To_addr, Msg) > > > > to send Msg to To_addr, thru' Server.... > > ....I'd like to learn how to add an attachment (MIME encoded ??) to this > > Msg, so that I can send mail with attachments confirming to mail > > standards on the net. > > Hi there, > > The existing MIME modules are not all that useful. There are two > additional third party modules that do the job for you: mimecntl (at > http://starship.python.net/crew/arcege/modules/mimecntl.html) and mimelib > (at http://mimelib.sourceforge.net/). > > With both, you can create MIME documents that can be sent as-is through > smtplib. > > For example: > > # MIME_document is the base class, MIME_recoder_f is specialized to > # encode large data to an external temporary file > from mimecntl import MIME_document, MIME_recoder_f, MIMEField > > # make some text to go with the attachment > mail_body = MIME_document("""\ > Hey there, this is the picture from July 4th that you wished to see. > """) > > # now load in the picture; basic data objects are treated as files > # so we read binary data blocks and write them to the MIME object > jpeg_file = open('fireworks.jpg', 'rb') > # we create a new encodable object, with a "content-type" of a JPEG > # image, and the name of the file > attachment = MIME_recoder_f( > type=MIMEField('Content-Type', 'image/jpeg', name='fireworks.jpg') > ) > jpeg_length = 0 > block = jpeg_file.read(1024) > while block: > jpeg_length = jpeg_length + len(block) > attachment.write(block) > block = jpeg_file.read(1024) > > # but we want to encode in base64 > encoded_attachment = attachment.encode('base64') > # the system does not add fields itself, it only does what you want > encoded_attachment['Content-Length'] = jpeg_length > > # now combine them together into a multipart document > message = MIME_document( (mail_body, attachment), > From=From, To=To_addr, Subject="Fourth of July Fireworks" > ) > > # send the document through your smtplib.SMTP object > conn.sendmail( > message['from'], # the "From" field of the message > tuple(message['to']), # multiple items in field (sendmail wants a tuple) > str(message) # the message as a complete string document > ) > > I hope this helps. > -Arcege -- ---------------------------------------------- Every oak tree started out as a couple of nuts who stood their ground. Anonymous ---------------------------------------------- From alan.gauld@bt.com Wed Oct 24 17:14:52 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 24 Oct 2001 17:14:52 +0100 Subject: [Tutor] Learning about other languages by using Python [S Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C02C@mbtlipnt02.btlabs.bt.co.uk> > Care to point out a really good Scheme language reference > online? The classic book: Structure and Interpretation of Computer Programs by Abelson and Sussman is available online and makes a pretty good Scheme intro. There is also an interactive tutor available if you visit the scheme homepage(www.schemers.org). It comes with an IDLE like development/debugging tool. Its called DR Scheme... Alan g. From claird@starbase.neosoft.com Wed Oct 24 17:51:08 2001 From: claird@starbase.neosoft.com (Cameron Laird) Date: Wed, 24 Oct 2001 11:51:08 -0500 (CDT) Subject: [Tutor] Re: help In-Reply-To: <20011024031033.22365.qmail@mailFA10.rediffmail.com> Message-ID: <200110241651.LAA10850@starbase.neosoft.com> > From bas_p@rediffmail.com Tue Oct 23 22:17:46 2001 > . > . > . > i am a beginner in python, i can do small program in command line, which includes control statements, class and objects but i dont know how to program it in an editor. please help me by sending some sample programs on it and python editor. > . > . > . Do you have access to the World-Wide Web? I think you'll want to read . Among other things, it recommends that you address your question to . From jeff@ccvcorp.com Wed Oct 24 17:49:02 2001 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed, 24 Oct 2001 09:49:02 -0700 Subject: [Tutor] use of WxPython class, method, etc References: Message-ID: <3BD6F0FE.68374215@ccvcorp.com> > > On Thu, 25 Oct 2001 03:56:40, "Adinda Praditya" wrote: > > I restarted over then. here's another story about my problem. From manual : > === > There are two different ways to use this class: > > You may derive a new class from wxTimer and override the Notify member to > perform the required action. Try something like this: ------------------------------- class MyTimer(wxTimer): def __init__(self): wxTimer.__init__(self) # just in case... def Notify(self): SomeOtherControl.AddText('Timer went off!') --------------------------------- Now, use this MyTimer class where you're currently trying to use a wxTimer. MyTimer *is* a wxTimer--but it's also got a newer Notify method, that actually does something. What exactly it does is up to you. :) I've also included an __init__() method, which does nothing other than call the base class (wxTimer) __init__(). This shouldn't be strictly necessary, as the base method should be called automatically if you don't define one in the derived class, but it doesn't hurt, and makes it a bit easier if you later decide that you need to do something special when setting up the timer (storing the start time, etc). > Did i miss something? I think the manual doesn't give me a clear definition > and syntax or i'm a stupid person! I still don't get it. Does anyone has a > better explanation to understand these stuff (how to use, work with class, method, > object) Please help me. The manual *is* a bit confusing--for starters, it's really written for C++, not Python, and even though most of the information carries straight over, it does require a bit of translating, which can be difficult if you know nothing of C++. It also assumes moderate familiarity with object-oriented programming and the typical terms in OOP. Any time you're told to "override this method", it really means "create a subclass of this class, and give that subclass a method with this name and call signature (number and type of parameters, return value, etc)". I wish I knew a site with a good description of OOP to recommend--maybe someone else can suggest something? > thank you, > > Adinda Praditya You're welcome. Hope that this was helpful for you. :) Jeff Shannon Technician/Programmer Credit International From glingl@aon.at Wed Oct 24 18:56:18 2001 From: glingl@aon.at (Gregor Lingl) Date: Wed, 24 Oct 2001 19:56:18 +0200 Subject: [Tutor] Learning about other languages by using Python [S References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C02C@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <3BD700C2.C694C7EB@rg16.asn-wien.ac.at> alan.gauld@bt.com schrieb: > There is also an interactive tutor available if > you visit the scheme homepage(www.schemers.org). > It comes with an IDLE like development/debugging > tool. Its called DR Scheme... > > Alan g. I'd really like IDLE to be a DR-Scheme like development/debugging tool. Until now it's far from that. Gregor L. From kromag@nsacom.net Wed Oct 24 20:21:29 2001 From: kromag@nsacom.net (kromag@nsacom.net) Date: Wed, 24 Oct 2001 12:21:29 -0700 (PDT) Subject: [Tutor] Number Coercion: I swear, I never laid a hand on it! Message-ID: <200110241921.f9OJLSY15949@pop.nsacom.net> Hi everybody, I have been trying to write a silly little menu script just to figure out how: -------------silly menu script------------- import os import string import sys menu_items={'edit': '\windows\command\edit.com', 'vim': '\vim\vim57\gvim.exe'} print 'menu choices' print menu_items.keys() choice = raw_input() if menu_items.has_key(choice): os.system('s%')% menu_items[choice] else: sys.exit('Sorry, try again.') ---------end silly menu script------------- For some reason, I get a problem with: os.system('s%')% menu_items[choice] which gives this number coercion error: -------------error------------------------- C:WINDOWSDESKTOP>python menu.py menu choices ['vim', 'edit'] vim Bad command or file name Traceback (most recent call last): File "menu.py", line 15, in ? os.system('s%')% menu_items[choice] TypeError: number coercion failed ---------end error------------------------- I stand confused. d From arcege@speakeasy.net Wed Oct 24 18:01:35 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Wed, 24 Oct 2001 13:01:35 -0400 Subject: [Tutor] Attachment to a mail message In-Reply-To: <01102421160800.04525@mercury.worli>; from lonetwin@yahoo.com on Wed, Oct 24, 2001 at 09:16:08PM +0530 References: <20011024091722.A990@speakeasy.net> <01102421160800.04525@mercury.worli> Message-ID: <20011024130135.B990@speakeasy.net> On Wed, Oct 24, 2001 at 09:16:08PM +0530, lonetwin wrote: > Hey Arcege > Thanx a lot for those links ...I'll just go ahead and use one of them > ...although I'll still be waiting for someone to give me a idea of doing this > with the std lib modules...just so that I know. You need to look at both MimeWriter and mimetools. This is an example from Breazley's "Python Essential Reference." I added some bits to help with your example. import sys import mimetools, mimetypes, MimeWriter # Open the output file and create a MimeWriter out = open("output.txt", "w") writer = MimeWriter.MimeWriter(out) # {Arcege: I added this to show your e-mail headers} writer.addheader('From', 'tommy@hometown.net') writer.addheader('To', 'santa@northpole.com') writer.addheader('Subject:', 'christmas list') # Start a multipart message writer.startmultipartbody('mixed') writer.flushheaders() for file in sys.argv[1:]: subpart = writer.nextpart() # Create a new sub-part # Attempt to guess the file's MIME type and encoding type, encoding = mimetypes.guess_type(file) if encoding: subpart.addheader("Content-encoding", encoding) # {Arcege: I think that this should not be indented} subpart.addheader("Content-transfer-encoding", "base64") if type: pout = subpartbody(type, [("name", file)]) else: pout = subpartbody("text/plain", [("name", file)]) infile = open(file, "rb") # Encode the raw data using base64 mimetools.encoding(infile, pout, 'base64') infile.close() # Clean up writer.lastpart() out.close() # {Arcege: this is for your help too} your smtplib.SMTP object conn.sendmail('tommy@hometown.net', ('santa@northpole.com',), open('output.txt', 'r').read()) # {Arcege: notice the MimeWriter object is really useless for reading # back the data} Also, the mimetools.Message object is not easily convertable to the a MimeWriter object (which is why the 'mimecntl' module was really created). Both 'mimecntl' and 'mimelib' convert MIME input to MIME output and with full modifications of the data (as one entity) between. For example, from the MimeWriter object, you cannot get access to, or change, the headers that you previously set. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | | Ailment info: http://www.speakeasy.org/~arcege/michaelwatch.html | From koen@behindthesofa.dhs.org Wed Oct 24 18:01:42 2001 From: koen@behindthesofa.dhs.org (Koen Bossers) Date: Wed, 24 Oct 2001 19:01:42 +0200 Subject: [Tutor] Number Coercion: I swear, I never laid a hand on it! References: <200110241921.f9OJLSY15949@pop.nsacom.net> Message-ID: <3BD6F3F6.7010302@behindthesofa.dhs.org> kromag@nsacom.net wrote: > Hi everybody, > > I have been trying to write a silly little menu script just to figure out how: > > For some reason, I get a problem with: > > os.system('s%')% menu_items[choice] > > which gives this number coercion error: > > -------------error------------------------- try: os.system('%s'% menu_items[choice]) instead.... Cheers, Koen -- Python@BehindTheSofa home of mapselect.py, dailycomic.py and others. http://behindthesofa.dhs.org ------------------------------- From shalehperry@home.com Wed Oct 24 18:04:40 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Wed, 24 Oct 2001 10:04:40 -0700 (PDT) Subject: [Tutor] Number Coercion: I swear, I never laid a hand on it! In-Reply-To: <200110241921.f9OJLSY15949@pop.nsacom.net> Message-ID: > > if menu_items.has_key(choice): > os.system('s%')% menu_items[choice] > else: > sys.exit('Sorry, try again.') > > ---------end silly menu script------------- > > For some reason, I get a problem with: > > os.system('s%')% menu_items[choice] > > which gives this number coercion error: > it's "%s", not vice versa. From scarblac@pino.selwerd.nl Wed Oct 24 18:03:46 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 24 Oct 2001 19:03:46 +0200 Subject: [Tutor] Number Coercion: I swear, I never laid a hand on it! In-Reply-To: <200110241921.f9OJLSY15949@pop.nsacom.net>; from kromag@nsacom.net on Wed, Oct 24, 2001 at 12:21:29PM -0700 References: <200110241921.f9OJLSY15949@pop.nsacom.net> Message-ID: <20011024190345.A17859@pino.selwerd.nl> On 0, kromag@nsacom.net wrote: > -------------silly menu script------------- > > import os > import string > import sys > > > menu_items={'edit': '\windows\command\edit.com', > 'vim': '\vim\vim57\gvim.exe'} Note that this won't work; backslashes have a special meaning, they're used to escape things so you can put special characters in a string (like \n means newline). A way to avoid this is to escape the backslashes; use \\ instead of \. > print 'menu choices' > print menu_items.keys() > > choice = raw_input() > > if menu_items.has_key(choice): > os.system('s%')% menu_items[choice] > else: > sys.exit('Sorry, try again.') > > ---------end silly menu script------------- > > For some reason, I get a problem with: > > os.system('s%')% menu_items[choice] I don't know if this is a typo or what, but the way it is written, it runs os.system('s%') first. 's%' is a command that probably doesn't exist, and os.system will return some number. The '%' operator used on numbers is the modulo operator; Python tries to interpret menu_items[choice] as another number but fails; it's a string. This gives a coercion error. What you meant was both '%s' instead of 's%', and to have the % command inside the os.system, not outside of it: os.system('%s' % menu_items[choice]) which happens to be exactly the same thing as os.system(menu_items[choice]) I think this reply is a bit obfuscated but I have to go, cooking :) -- Remco Gerlich From kromag@nsacom.net Wed Oct 24 21:13:46 2001 From: kromag@nsacom.net (kromag@nsacom.net) Date: Wed, 24 Oct 2001 13:13:46 -0700 (PDT) Subject: Fwd: Re: [Tutor] Number Coercion: I swear, I never laid a hand on it! Message-ID: <200110242013.f9OKDkY23183@pop.nsacom.net> Forwarded From: kromag@nsacom.net > Remco Gerlich said: > > > > > > > menu_items={'edit': 'windowscommandedit.com', > > > 'vim': 'vimvim57gvim.exe'} > ^ ^ ^ > It's TWIG! I swear! :-) > > > > > Note that this won't work; backslashes have a special meaning, they're used > > to escape things so you can put special characters in a string (like n > > means newline). > > I actually put double backslashes in the script: my webmail program (twig) > removes them for some reason. Sorry for the confusion! > > > > > I don't know if this is a typo or what, but the way it is written, it runs > > os.system('s%') first. 's%' is a command that probably doesn't exist, and > > os.system will return some number. > > Simple ascii cannot express the depths of my self-loathing at this point. > Yes, it was a typo. > > > > > os.system('%s' % menu_items[choice]) > > > > which happens to be exactly the same thing as > > > > os.system(menu_items[choice]) > > > > > > I think this reply is a bit obfuscated but I have to go, cooking :) > > Your reply is crystal. I don't know why I persist in placing my substitutions > outside of the parentheses. Sorry for all the trouble folks. > > d > > > > > -- > > Remco Gerlich > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > From shalehperry@home.com Wed Oct 24 18:49:01 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Wed, 24 Oct 2001 10:49:01 -0700 (PDT) Subject: [Tutor] Number Coercion: I swear, I never laid a hand on it! In-Reply-To: <200110242002.f9OK2IY22097@pop.nsacom.net> Message-ID: > > menu choices > ['vim', 'edit'] > vim > Bad command or file name > Traceback (most recent call last): > File "menu.py", line 14, in ? > os.system("s%")% menu_items[choice] > TypeError: number coercion failed > which takes us back to Remco's mail. The syntax is: "%s" % menu_items[choice]. This is analogous to C's sprintf (and printf, etc). I always say this on the list and will say it again. When things break, run the interpreter and play in it. >>> foo = 'Sean' >>> "%s" % foo 'Sean' >>> def bar(input): ... print input ... >>> bar("%s") % foo %s Traceback (innermost last): File "", line 1, in ? TypeError: bad operand type(s) for % Here you can see the % error. > The confusing thing to me is: > >>>> menu_items={'edit': "\windows\command\edit.com", > 'vim': "\vim\vim57\gvim.exe"} >>>> choice="vim" >>>> choice > 'vim' >>>> menu_items[choice] > '\vim\vim57\gvim.exe' > > seems to be giving the correct answer! Am I nuts? >>> t = '\vim\vim57\gvim.exe' >>> print t im im57\gvim.exe >>> the backslash is used to escape characters. You can solve this in one of two ways: >>> t = r'\vim\vim57\gvim.exe' >>> t '\\vim\\vim57\\gvim.exe' >>> t = '\\vim\\vim57\\gvim.exe' >>> t '\\vim\\vim57\\gvim.exe' The 'r' before the quotes says "This is a raw string, do not look at it, just save it". You see this most in python when people are doing regular expressions which have all kinds of odd characters. The moral? Watch the syntax a little more and when things get confusing use the interpreter to find the answer. What makes python (and langauges like it) great is that you have instant feedback. From Charlie@begeistert.org Wed Oct 24 22:29:53 2001 From: Charlie@begeistert.org (Charlie Clark) Date: Wed, 24 Oct 2001 23:29:53 +0200 Subject: [Tutor] SGML-Parser: was finding title tag Message-ID: <1003958993_PM_BeOS.Charlie@begeistert.org> >Dear Samir, > >I'm slightly busy at the moment, but I'll be able to answer your question >tonight. I'm forwarding this to the other tutors on the mailing list, so >that someone has a chance to answer you. Best of wishes! > > >---------- Forwarded message ---------- >Date: Tue, 16 Oct 2001 17:22:14 +1000 (EST) >From: Samir Patel >To: Danny Yoo >Subject: Re: [Tutor] finding title tag > >hi, >thanx a lot for the help... >i am confused with the use of class ....as i want to find links at the >depth of 3 or more how can i recursively call this method..... > >also in following soln of yours it will separate links and title for that >links ..so i will not be able to keep track of which title belongs to >which link....and also if there's no title then i have to get the text of >the link > Hello Samir, is this still acute? I read the message last week before I had to leave for München and run BeGeistert at the weekend. Back at my machine I feel I owe it to the list and Danny in particular to try and help you out: it took me a while to get used to using the HTML-Parser but I've since then been parsing HTML like a maniac... I've never come across "title" as an attribute in an anchor tag. As is a tag, I think "title" is probably not allowed... but there's lots of sub-standard HTML out there. I've had to collect lists of links and like you I need to be able to keep various attributes together. The solution is quite simply to put the attributes into a dictionary and put the dictionary in a list. It only needs some slight modifications to the code from sgmllib import SGMLParser class AnchorParser(SGMLParser): """This class pays attention to anchor tags. Once we feed() a document into an AnchorParser, we'd have the hrefs in the 'anchorlist' attribute, and the titles in the 'titlelist' attribute.""" def __init__(self): SGMLParser.__init__(self) self.anchor = {'link'.'', 'title':'} # this a dictionary for each anchor self.anchorlist = [] def start_a(self, attributes): """For each anchor tag, pay attention to the href and title attributes.""" href, title = '', '' for name, value in attributes: if name == 'href': href = value if name == 'title': title = value self.anchor['link'] = href self.anchor['title'] = title def end_a(self): self.anchorlist.append(self.anchor) # store the anchor in a list self.anchor = {'url':'', 'title:''} # reset the dictionary, ready for the next anchor Running this should work a bit like this: biglist =[] c = AnchorParser() c.feed(src) # where src is the url to be parsed c.close l = c.anchorlist biglist.append.append(l) print l '[{'url':'http://www.begeistert.org', 'title':'some title'}] Looping over the list should be straightforward: for item in l: src_url = item['url'] src = urllib.urlopen(src_url) c = AnchorParser() l = c.anchorlist biglist.append.append(l) Put this into nice little functions and repeat as often as necessary. I haven't tested this but it shouldn't take much to get it to work. Can anyone tell me how to loop through the list with the new iterator function? Charlie From dyoo@hkn.eecs.berkeley.edu Thu Oct 25 07:05:32 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 24 Oct 2001 23:05:32 -0700 (PDT) Subject: [Tutor] RExec woes In-Reply-To: <20011023132331.J31102@marilyn> Message-ID: <Pine.LNX.4.21.0110242243370.14566-100000@hkn.eecs.berkeley.edu> On Tue, 23 Oct 2001, Scott Moynes wrote: > As a quick example, here's approximately what I'm trying to > accomplish: > > >>> r=rexec.RExec() > >>> m=r.add_module('sys') > >>> s=StringIO.StringIO() > >>> m.__dict__['stdin']=s > >>> r.r_exec('print "something"') > something > >>> s.getvalue() > '' Quick solution: ### import rexec, StringIO r = rexec.RExec() r.make_delegate_files() s = StringIO.StringIO() r.restricted_stdout = s r.s_exec("import sys") r.s_exec("sys.stdout.write('hello world')") ### Rambling, incoherant explanation of what in the world made me do it this way is below. *grin* Ok, I've been staring at the rexec code a little bit, and I think I understand it better now. There's one part of the code that's really important, in make_delegate_files(): ### def make_delegate_files(self): s = self.modules['sys'] self.delegate_stdin = FileDelegate(s, 'stdin') self.delegate_stdout = FileDelegate(s, 'stdout') self.delegate_stderr = FileDelegate(s, 'stderr') self.restricted_stdin = FileWrapper(sys.stdin) self.restricted_stdout = FileWrapper(sys.stdout) self.restricted_stderr = FileWrapper(sys.stderr) ### Remember that old trick with swapping sys.stdout with a StringIO() instance? Well, that's exactly what rexec does. *grin* Whenever we run a s_exec() or s_eval(), rexec() actually does swap and save the old sys.stdin/stdout, replace them with their FileWrapped equivalents, does its restricted execution stuff, and swaps them back. That's all the stuff that rexec.set_files(), rexec.reset_files(), and rexec.save_files() is all about. To make things work, it might seem that the simplest thing to do is to redefine our RExec()'s restricted_stdout to our own StringIO instance, like this: ### import rexec, StringIO r = rexec.RExec() s = StringIO.StringIO() r.restricted_stdout = s r.s_exec("import sys") r.s_exec("sys.stdout.write('hello world')") ### But this has a REALLY subtle bug, having to with rexec.set_files(): ### def set_files(self): if not hasattr(self, 'save_stdin'): self.save_files() if not hasattr(self, 'delegate_stdin'): self.make_delegate_files() ### The bug is that, when we first call set_files(), there is no 'delegate_stdin' attribute, since make_delegate_files() hasn't been called yet. Why this is, I have no clue. The quick fix is to call make_delegate_files() at least once, before doing any foolery: ### import rexec, StringIO r = rexec.RExec() r.make_delegate_files() s = StringIO.StringIO() r.restricted_stdout = s r.s_exec("import sys") r.s_exec("sys.stdout.write('hello world')") ### But that was convoluted. Can anyone with rexec experience explain why make_delegate_files() isn't called in RExec's constructor? Hope this helps! From dyoo@hkn.eecs.berkeley.edu Thu Oct 25 07:09:10 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 24 Oct 2001 23:09:10 -0700 (PDT) Subject: [Tutor] RExec woes [Capturing rexec's output] In-Reply-To: <Pine.LNX.4.21.0110242243370.14566-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.21.0110242306500.14566-100000@hkn.eecs.berkeley.edu> On Wed, 24 Oct 2001, Danny Yoo wrote: > On Tue, 23 Oct 2001, Scott Moynes wrote: > > > As a quick example, here's approximately what I'm trying to > > accomplish: > > > > >>> r=rexec.RExec() > > >>> m=r.add_module('sys') > > >>> s=StringIO.StringIO() > > >>> m.__dict__['stdin']=s > > >>> r.r_exec('print "something"') > > something > > >>> s.getvalue() > > '' > > Quick solution: > > ### > import rexec, StringIO > r = rexec.RExec() > r.make_delegate_files() > s = StringIO.StringIO() > r.restricted_stdout = s > r.s_exec("import sys") > r.s_exec("sys.stdout.write('hello world')") > ### Oh, by the way, this also works with the regular "print" statement: ### import rexec import StringIO r = rexec.RExec() r.make_delegate_files() ## A mystery to me why this isn't ## documented better... *sigh* s = StringIO.StringIO() r.restricted_stdout = s r.s_exec("print 'hello world'") print "Here's what we captured: ", s.getvalue() ### Sorry about complicating matters... From alan.gauld@bt.com Thu Oct 25 10:47:42 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 25 Oct 2001 10:47:42 +0100 Subject: [Tutor] Number Coercion: I swear, I never laid a hand on it! Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C02E@mbtlipnt02.btlabs.bt.co.uk> > if menu_items.has_key(choice): > os.system('s%')% menu_items[choice] I think you mean os.system('%s')... Alan g. From kaffeen@mac.com Thu Oct 25 14:05:13 2001 From: kaffeen@mac.com (Chris Scott) Date: Thu, 25 Oct 2001 09:05:13 -0400 Subject: [Tutor] Newbie with aspirations... Message-ID: <B7FD8649.2F0%kaffeen@mac.com> Howdy folks, Total newbie with high aspirations is looking for pointers on learning to program games in python. I've read it's a great language to learn, quick to pick-up, and very fast in terms of development time. That said, can anyone point me in the direction of a good tutorial where I can start learning to program games? I have tried pygame.org, but now tuts there. To date I've been working in Lingo (Macromedia Director's internal scripting language, looks quite similar to Python, actually...) Suggestions would be much appreciated, thanks! - Chris From sheila@thinkspot.net Thu Oct 25 15:52:56 2001 From: sheila@thinkspot.net (Sheila King) Date: Thu, 25 Oct 2001 07:52:56 -0700 Subject: [Tutor] Newbie with aspirations... In-Reply-To: <B7FD8649.2F0%kaffeen@mac.com> References: <B7FD8649.2F0%kaffeen@mac.com> Message-ID: <715501476A8@kserver.org> On Thu, 25 Oct 2001 09:05:13 -0400, Chris Scott <kaffeen@mac.com> wrote about [Tutor] Newbie with aspirations...: :That said, can anyone point me in the direction of a good tutorial where I :can start learning to program games? I have tried pygame.org, but now tuts :there. To date I've been working in Lingo (Macromedia Director's internal :scripting language, looks quite similar to Python, actually...) Suggestions :would be much appreciated, thanks! Here is a list of beginner resources, including tutorials: http://www.thinkspot.net/materdei/apcompsci/python/index.html -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From dsh8290@rit.edu Thu Oct 25 16:02:34 2001 From: dsh8290@rit.edu (dman) Date: Thu, 25 Oct 2001 11:02:34 -0400 Subject: [Tutor] [OT] Bay PIGgies hijacked? Message-ID: <20011025110234.A29346@harmony.cs.rit.edu> I'm sending this to the list because IIRC there are some people on this list that are part of the Bay PIGgies group. I sent a private message to someone earlier, but they're not part of the baypiggies. ---- I just tried to follow a link to an intro on using libglade with python on www.baypiggies.org, but ended up at a porn site >8^p. Did someone screw up the DNS records? Is there a way I can get to the site (is it a static IP that you can share)? BTW, the link was on an old GNOME news page found by Google. The news item is dated "Nov. 21" so it must be at least almost a year old. TIA, -D From dsh8290@rit.edu Thu Oct 25 17:04:05 2001 From: dsh8290@rit.edu (dman) Date: Thu, 25 Oct 2001 12:04:05 -0400 Subject: [Tutor] Learning about other languages by using Python [S In-Reply-To: <XFMail.20011024011716.shalehperry@home.com>; from shalehperry@home.com on Wed, Oct 24, 2001 at 01:17:16AM -0700 References: <Pine.LNX.4.21.0110232237110.15261-300000@hkn.eecs.berkeley.edu> <XFMail.20011024011716.shalehperry@home.com> Message-ID: <20011025120403.A29392@harmony.cs.rit.edu> On Wed, Oct 24, 2001 at 01:17:16AM -0700, Sean 'Shaleh' Perry wrote: | Care to point out a really good Scheme language reference online? I | should write one of those myself. I missed out on all of the fun | reasons people took CS. There's the R5RS document. It is the standard that defines the core of scheme. It stands for Revised Revised Revised Revised Revised Reference on Scheme (or something like that). It is not a tutorial in any way. It also shows that pure scheme isn't really useful for real-world programming, but I know that the Guile people have added losts to the library to make it useful. -D From scarblac@pino.selwerd.nl Thu Oct 25 17:25:31 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 25 Oct 2001 18:25:31 +0200 Subject: [Tutor] Newbie with aspirations... In-Reply-To: <B7FD8649.2F0%kaffeen@mac.com>; from kaffeen@mac.com on Thu, Oct 25, 2001 at 09:05:13AM -0400 References: <B7FD8649.2F0%kaffeen@mac.com> Message-ID: <20011025182531.A19750@pino.selwerd.nl> On 0, Chris Scott <kaffeen@mac.com> wrote: > Howdy folks, > Total newbie with high aspirations is looking for pointers on learning to > program games in python. I've read it's a great language to learn, quick to > pick-up, and very fast in terms of development time. Yup. > That said, can anyone point me in the direction of a good tutorial where I > can start learning to program games? I have tried pygame.org, but now tuts > there. I don't know specific tutorials on learning to program games. One of the obvious reasons is that programming games isn't, by itself, very different from programming in general. It also depends on the type of game - a chess program and Quake are both games, but they don't have much programming in common. In my opinion, you should follow the normal programming tutorials first. After them, pick either a simple type of game that doesn't require much graphics as a first project, or a graphical app that's not a game. You'll need some sort of first project that you can handle; you can expand it later so start very small. You can ask for hints here. Once you know the basics a bit, also try to get into pygame as soon as you can understand the things that are explained - pygame is really neat. Actually, there is a link to a pygame tutorial on pygame.org, it explains the very simple example game Chimp line by line. Expanding Chimp could be a first project. Generic Python tutorials for non-programmers are listed at http://www.python.org/doc/Newbies.html . > To date I've been working in Lingo (Macromedia Director's internal > scripting language, looks quite similar to Python, actually...) Suggestions > would be much appreciated, thanks! I don't know Lingo. It's always good to know many languages (but try not to confuse them when actually programming in one). -- Remco Gerlich From samir@hotmail.com Thu Oct 25 17:39:01 2001 From: samir@hotmail.com (samir shehata) Date: Thu, 25 Oct 2001 16:39:01 +0000 Subject: [Tutor] (no subject) Message-ID: <LAW2-F72gl4rhYQYx3G00013dee@hotmail.com> <html><div style='background-color:'><DIV> <P>confirm 322266<BR><BR></P></DIV></div><br clear=all><hr>Get your FREE download of MSN Explorer at <a href='http://go.msn.com/bql/hmtag_itl_EN.asp'>http://explorer.msn.com</a><br></html> From bl_mark@hotmail.com Thu Oct 25 17:39:08 2001 From: bl_mark@hotmail.com (Barbara Mark) Date: Thu, 25 Oct 2001 11:39:08 -0500 Subject: [Tutor] Newbie - Not reading file Message-ID: <F2001c00goZolmRBaYF00012d49@hotmail.com> Hello, I am a programming newbie and Python newbie. I need some very basic help with my first program. I've looked through some of the archives, and someone has borrowed my copy of "Learning Python." The program does not seem to be reading in the file very well, although the imported function calculation works fine. It will do a correct calculation if I offer it a number, but it will not grab the numbers from the opened file. I've tried many things, so what I have below is just a sample. Please help, tell me what I'm doing wrong. The program is: TaxProgram The function is: Tax8.py The file is: Incomes.dat *******I have tried many, but a version of the program reads: import sys import Tax8 t = Tax8.tax x = open('incomes.dat', 'r+') while x > 0: t(x) *******Again, I have tried many, but a version of the function reads: def tax(x): #calculates tax for input income print x r = [] if 0 < x < 20000: r = x*0.1 elif 20000 < x < 60000: r = (20000 * 0.1) + ((x-20000) * 0.15) elif 60000 < x < 200000: r = (20000 * 0.1) + (40000 * 0.15) + ((x-60000) * 0.25) else: r = (20000 * 0.1) + (40000 * 0.15) + (200000 * 0.25) + ((x-200000) * 0.3) print r return r ******A sample incomes.dat file may read: 10000 15000 50000 0 ** Any help would be appreciated. Thanks. Blm _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp From boud@valdyas.org Thu Oct 25 17:42:20 2001 From: boud@valdyas.org (Boudewijn Rempt) Date: Thu, 25 Oct 2001 18:42:20 +0200 Subject: [Tutor] Newbie with aspirations... In-Reply-To: <20011025182531.A19750@pino.selwerd.nl> References: <B7FD8649.2F0%kaffeen@mac.com> <20011025182531.A19750@pino.selwerd.nl> Message-ID: <200110251642.f9PGgLa28505@calcifer.valdyas.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Thursday 25 October 2001 18:25, Remco Gerlich wrote: > On 0, Chris Scott <kaffeen@mac.com> wrote: > > Howdy folks, > > Total newbie with high aspirations is looking for pointers on learnin= g to > > program games in python. I've read it's a great language to learn, qu= ick > > to pick-up, and very fast in terms of development time. > > Yup. > > > That said, can anyone point me in the direction of a good tutorial wh= ere > > I can start learning to program games? I have tried pygame.org, but n= ow > > tuts there. > > I don't know specific tutorials on learning to program games. One of th= e > obvious reasons is that programming games isn't, by itself, very differ= ent > from programming in general. It also depends on the type of game - a ch= ess > program and Quake are both games, but they don't have much programming = in > common. > > In my opinion, you should follow the normal programming tutorials first= =2E > After them, pick either a simple type of game that doesn't require much > graphics as a first project, or a graphical app that's not a game. > I just remembered that the original tutorial that comes with the C++ Qt l= ibarary describes building a game. Every stage has been ported to PyQt (you can find the various files in the examples directory of PyQt.) The Qt library (both Windows and Unix/X11) can be had at: http://www.trolltech.com And the PyQt bindings at: http://www.thekompany.com/projects/pykde - --=20 Boudewijn Rempt | http://www.valdyas.org -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE72EDsN8fj6DnPxOgRAnwxAJ9f1KJ9lkj4zsnqZh6/kXDhCgA8igCguFYy nnlb73CHj1TdDVIPvtOpRzM=3D =3D5bd5 -----END PGP SIGNATURE----- From scarblac@pino.selwerd.nl Thu Oct 25 17:53:33 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 25 Oct 2001 18:53:33 +0200 Subject: [Tutor] Newbie - Not reading file In-Reply-To: <F2001c00goZolmRBaYF00012d49@hotmail.com>; from bl_mark@hotmail.com on Thu, Oct 25, 2001 at 11:39:08AM -0500 References: <F2001c00goZolmRBaYF00012d49@hotmail.com> Message-ID: <20011025185333.A19854@pino.selwerd.nl> On 0, Barbara Mark <bl_mark@hotmail.com> wrote: > Hello, > I am a programming newbie and Python newbie. I need some very basic help > with my first program. I've looked through some of the archives, and > someone has borrowed my copy of "Learning Python." > The program does not seem to be reading in the file very well, although the > imported function calculation works fine. It will do a correct calculation > if I offer it a number, but it will not grab the numbers from the opened > file. I've tried many things, so what I have below is just a sample. > Please help, tell me what I'm doing wrong. > > The program is: TaxProgram > The function is: Tax8.py > The file is: Incomes.dat > > *******I have tried many, but a version of the program reads: > import sys > import Tax8 > > t = Tax8.tax > > x = open('incomes.dat', 'r+') > > while x > 0: > t(x) What happens here is that the file is opened, and the open file is called x. Nothing is actually read yet. You can read a line of the file with x.readline(), then you have to do something with the line. Also, it will be a string first, not a number, so you have to change it into an int. This should work: import Tax8 # sys instead used t = Tax8.tax # This isn't actually necessary, but does no harm x = open('incomes.dat', 'r') # For later, try giving your files better names :-) while 1: # We're going to repeat this until the number is 0 line = x.readline() number = int(line) if number == 0: # End of file, leave the while loop break t(number) > *******Again, I have tried many, but a version of the function reads: > def tax(x): #calculates tax for input income > > print x > r = [] > > if 0 < x < 20000: > r = x*0.1 > > elif 20000 < x < 60000: > r = (20000 * 0.1) + ((x-20000) * 0.15) > > elif 60000 < x < 200000: > r = (20000 * 0.1) + (40000 * 0.15) + ((x-60000) * 0.25) > > else: > r = (20000 * 0.1) + (40000 * 0.15) + (200000 * 0.25) + ((x-200000) * 0.3) > > print r > > return r One comment: usually a function either prints a result, or returns it so it can be used elsewhere, but not both. In this case, the program above doesn't do anything with the result and relies on the function to print it; it would perhaps be better if you didn't print it here, but instead wrote 'print t(number)' in the while loop above. Then you could use the same function somewhere else, if you didn't want to print the results, but store them or use them in some calculation. > ******A sample incomes.dat file may read: > 10000 > 15000 > 50000 > 0 And one comment here: this works, ending the file with 0. Until you actually get a zero income in there! Now .readline() on a file returns the empty string ('') when you call it at the end of the file. So you could also end the loop like this: while 1: line = x.readline() if line == '': break number = int(line) ... (etc) And then you don't need to end your data file with a zero. > ** Any help would be appreciated. > > Thanks. Blm Hope this helps. -- Remco Gerlich From shalehperry@home.com Thu Oct 25 17:56:17 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Thu, 25 Oct 2001 09:56:17 -0700 (PDT) Subject: [Tutor] Newbie - Not reading file In-Reply-To: <F2001c00goZolmRBaYF00012d49@hotmail.com> Message-ID: <XFMail.20011025095617.shalehperry@home.com> > import sys > import Tax8 > > t = Tax8.tax > > x = open('incomes.dat', 'r+') > opening a file is only the first step. All that does is prepare the file to be read later. Think of this as getting a manilla folder out of a cabinet. You have it in your hand but have not had a chance to look though its contents yet. Have a look at a few of the online tutorials for inspiration. From rufmetal@home.com Thu Oct 25 21:55:56 2001 From: rufmetal@home.com (Chris Keelan) Date: Thu, 25 Oct 2001 15:55:56 -0500 Subject: [Tutor] Learning about other languages by using Python [S In-Reply-To: <20011025120403.A29392@harmony.cs.rit.edu> References: <Pine.LNX.4.21.0110232237110.15261-300000@hkn.eecs.berkeley.edu> <XFMail.20011024011716.shalehperry@home.com> <20011025120403.A29392@harmony.cs.rit.edu> Message-ID: <01102515555601.08643@tygesen> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Thursday 25 October 2001 11:04, dman wrote: > There's the R5RS document. It is the standard that defines the core > of scheme. It stands for Revised Revised Revised Revised Revised > Reference on Scheme (or something like that). It is not a tutorial in > any way. It also shows that pure scheme isn't really useful for > real-world programming, but I know that the Guile people have added > losts to the library to make it useful. This is a good tutorial: http://www.cs.rice.edu/~dorai/t-y-scheme/t-y-scheme.html This is a good overview: http://www.nmt.edu/tcc/help/lang/lisp/intro.txt This is an amzing site, if you're new to programming. While I agree with dman that Python might be more useful for 'real world' stuff, Scheme is an excellent way to directly approach computer science issues, and the two are usually taught concurrently. http://www.htdp.org/2001-09-22/ - - Chris -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE72Hxis7Brp8Mn7wcRAtSwAKCBtqBA8sMUfETRCb/e4zjwREDnZQCeK81d rRzHmOlKDD/G1CvXPbMl3/0= =Fmk+ -----END PGP SIGNATURE----- From dyoo@hkn.eecs.berkeley.edu Thu Oct 25 22:31:36 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 25 Oct 2001 14:31:36 -0700 (PDT) Subject: [Tutor] Newbie with aspirations... In-Reply-To: <715501476A8@kserver.org> Message-ID: <Pine.LNX.4.21.0110251422440.32442-100000@hkn.eecs.berkeley.edu> On Thu, 25 Oct 2001, Sheila King wrote: > On Thu, 25 Oct 2001 09:05:13 -0400, Chris Scott <kaffeen@mac.com> wrote > about [Tutor] Newbie with aspirations...: > > :That said, can anyone point me in the direction of a good tutorial where I > :can start learning to program games? I have tried pygame.org, but now tuts The Pygame web site does have a beginner's "Chimpanzee" tutorial on pygame.org, http://pygame.seul.org/docs/tut/ChimpLineByLine.html as well as a "newbies" guide: http://pygame.org/docs/tut/newbieguide.html But from looking at both docs, it appears that both assume some experience with Python. If you're unfamiliar with Python itself, it might be a good approach to try learning Python first before using it to write graphical games. Another good link for Python introductions is here: http://python.org/doc/Newbies.html Please feel free to ask questions about pygame here; I'm sure there are a lot of people who are interested in playing around with games. Good luck! From dyoo@hkn.eecs.berkeley.edu Thu Oct 25 22:52:55 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 25 Oct 2001 14:52:55 -0700 (PDT) Subject: [Tutor] [OT] Bay PIGgies hijacked? In-Reply-To: <20011025110234.A29346@harmony.cs.rit.edu> Message-ID: <Pine.LNX.4.21.0110251432110.32442-100000@hkn.eecs.berkeley.edu> On Thu, 25 Oct 2001, dman wrote: > I just tried to follow a link to an intro on using libglade with > python on www.baypiggies.org, but ended up at a porn site >8^p. Did > someone screw up the DNS records? Is there a way I can get to the > site (is it a static IP that you can share)? Hi dman, Yeah, we know about this. The domain got hijacked before Baypiggies was able to renew the record. As a result, I think Baypiggies is trying to redirect the baypiggies.org web site to: http://deirdre.org/baypiggies/ It's not up yet, but it'll be up soon. In the meantime, if you see any links to http://baypiggies.org on a website, please notify the webmaster to link Baypiggies to http://deirdre.org/baypiggies/, so that we can route around the damage. From mjyuen@hotmail.com Fri Oct 26 06:53:10 2001 From: mjyuen@hotmail.com (Mike Yuen) Date: Thu, 25 Oct 2001 23:53:10 -0600 Subject: [Tutor] String punctuation Message-ID: <F132zbxW3Bt8FeHQYTT000086e4@hotmail.com> Hi, i'm trying to figure how the string function punctuation works. I'm hoping that it will remove comma's, periods and other stuff from my strings. For some reason, I keep getting an attribute error. Can anyone tell me how to use this? Speak to me like i'm a 10 year old. I'm very new at this stuff. Thanks, Mike _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp From r.b.rigilink@chello.nl Fri Oct 26 07:44:51 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Fri, 26 Oct 2001 08:44:51 +0200 Subject: [Tutor] String punctuation References: <F132zbxW3Bt8FeHQYTT000086e4@hotmail.com> Message-ID: <3BD90663.6E41A8D@chello.nl> Mike Yuen wrote: > > Hi, i'm trying to figure how the string function punctuation works. I'm > hoping that it will remove comma's, periods and other stuff from my strings. > > For some reason, I keep getting an attribute error. Can anyone tell me how > to use this? Speak to me like i'm a 10 year old. I'm very new at this > stuff. > > Thanks, > Mike > Hi Mike, Unfortunately, punctuation is not a function of the string module, but just an attribute (variable) of that module that holds a string containing all punctuation characters. Here's an interactive session showing some of the thing you could do with it. >>> import string >>> print string.punctuation !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ >>> '.' in string.punctuation 1 >>> 'a' in string.punctuation 0 Let's build a function that checks to see if a character is a punctuation character >>> def is_punct_char(char): ... '''check if char is punctuation char''' ... if char in string.punctuation: ... return 1 ... else: ... return 0 ... >>> is_punct_char('.') 1 >>> is_punct_char('a') 0 This function can be made a little shorter >>> def is_punct_char(char): #shorter version ... '''check if char is punctuation char''' ... return char in string.punctuation ... >>> is_punct_char('.') 1 >>> is_punct_char('a') 0 Let's use this function to remove punctuation characters from a string >>> my_string = 'a string, not too long, containing "#$%&" characters.' >>> my_string 'a string, not too long, containing "#$%&" characters.' >>> new_string = '' >>> for char in my_string: ... if not is_punct_char(char): ... new_string = new_string+char ... >>> new_string 'a string not too long containing characters' Here's a slightly modified version >>> def is_not_punct_char(char): ... '''check if char is not punctuation char''' ... return not is_punct_char(char) ... >>> is_not_punct_char('.') 0 >>> is_not_punct_char('a') 1 >>> new_string = '' >>> for char in my_string: ... if is_not_punct_char(char): ... new_string = new_string+char ... >>> new_string 'a string not too long containing characters' This is probably what you wanted to get. But, to wet your appetite for more, here's some magic with the build in function 'filter'. This function does the same thing as the loop we've just written. Have a look at the Python documentation to see if you can fuigure out why this works. >>> new_string = filter(is_not_punct_char, my_string) >>> new_string 'a string not too long containing characters' Hope this helps, Roeland -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From scarblac@pino.selwerd.nl Fri Oct 26 07:35:15 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Fri, 26 Oct 2001 08:35:15 +0200 Subject: [Tutor] String punctuation In-Reply-To: <F132zbxW3Bt8FeHQYTT000086e4@hotmail.com>; from mjyuen@hotmail.com on Thu, Oct 25, 2001 at 11:53:10PM -0600 References: <F132zbxW3Bt8FeHQYTT000086e4@hotmail.com> Message-ID: <20011026083515.A20684@pino.selwerd.nl> On 0, Mike Yuen <mjyuen@hotmail.com> wrote: > Hi, i'm trying to figure how the string function punctuation works. I'm > hoping that it will remove comma's, periods and other stuff from my strings. Hi. string.punctuation is not a function, it's a string containing punctuation: >>> import string >>> print string.punctuation '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' > For some reason, I keep getting an attribute error. Can anyone tell me how > to use this? Speak to me like i'm a 10 year old. I'm very new at this > stuff. I'll show the simplest way then. If we have a string s, and we want to remove all the characters that are in string.punctuation from it, one way is to go through each of the characters in string.punctuation in turn, and remove it from the string. You can remove characters by replacing them with the empty string. So: import string def delete_punctuation(s): for char in string.punctuation: s = string.replace(s, char, '') return s print delete_punctuation("It's *not* 'you're' party, that's a 'typo'.") # prints # Its not youre party thats a typo -- Remco Gerlich From bwinton@tor.dhs.org Fri Oct 26 14:37:20 2001 From: bwinton@tor.dhs.org (Blake Winton) Date: Fri, 26 Oct 2001 09:37:20 -0400 Subject: [Tutor] String punctuation In-Reply-To: <3BD90663.6E41A8D@chello.nl> Message-ID: <EHEPLGFHKAPDEDKIBONMEEOECAAA.bwinton@tor.dhs.org> > This is probably what you wanted to get. But, to wet your appetite for > more, here's some magic with the build in function 'filter'. This > function does the same thing as the loop we've just written. Have a look > at the Python documentation to see if you can fuigure out why this > works. > > >>> new_string = filter(is_not_punct_char, my_string) > >>> new_string > 'a string not too long containing characters' And, just cause I wanted a chance to play around with a new feature, we can also write: Python 2.2a3 (#1, Sep 16 2001, 12:18:17) [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import string >>> my_string = 'a string, not too long, containing "#$%&" characters.' >>> "".join( [x for x in my_string if x not in string.punctuation] ) 'a string not too long containing characters' But I'm not going to explain how this one works, other than to say that I much prefer this version to the one using filter. Well, okay if you really want to know, email me, and I'll try to explain it in a little more detail. Later, Blake. From danny.kohn@systematik.se Fri Oct 26 15:08:06 2001 From: danny.kohn@systematik.se (Danny Kohn) Date: Fri, 26 Oct 2001 16:08:06 +0200 Subject: [Tutor] Why different behaviours? In-Reply-To: <EHEPLGFHKAPDEDKIBONMEEOECAAA.bwinton@tor.dhs.org> Message-ID: <OGEPIJONPINEELIFKPBOEEFFEBAA.danny.kohn@systematik.se> Hi. Why does: import string, sys f=3Dopen('d:/Dokument/Programprojekt/pythonworks/projects/H2/Lexicon.txt'= , 'r') line =3D f.readline() print line and: import string, sys f=3Dopen('d:/Dokument/Programprojekt/pythonworks/projects/H2/Lexicon.txt'= , 'r') for line in f.readline(): print line does not give the same result? Also, what would be the way to read line after line until end of file. = How to detect end of file when reading a sequential file this way? /Danny From bwinton@tor.dhs.org Fri Oct 26 15:04:40 2001 From: bwinton@tor.dhs.org (Blake Winton) Date: Fri, 26 Oct 2001 10:04:40 -0400 Subject: [Tutor] Why different behaviours? In-Reply-To: <OGEPIJONPINEELIFKPBOEEFFEBAA.danny.kohn@systematik.se> Message-ID: <EHEPLGFHKAPDEDKIBONMEEOFCAAA.bwinton@tor.dhs.org> > Why does: > import string, sys > f=open('d:/Dokument/Programprojekt/pythonworks/projects/H2/Lexicon > .txt', 'r') > line = f.readline() > print line This reads the first line, and prints it. > import string, sys > f=open('d:/Dokument/Programprojekt/pythonworks/projects/H2/Lexicon > .txt', 'r') > for line in f.readline(): > print line This reads the first line, sets the "line" variable to each character in turn, and prints each of them. > Also, what would be the way to read line after line until end of > file. How to detect end of file when reading a sequential file this way? Your second example is close, but you need to use f.readlines() instead of f.readline(). And the end of the file will end the for loop, so you don't have to worry about it. Later, Blake. From webmaster@garymgordon.com Fri Oct 26 15:29:46 2001 From: webmaster@garymgordon.com (Gary M. Gordon) Date: Fri, 26 Oct 2001 09:29:46 -0500 Subject: [Tutor] Which one of our FREE website enhancements would you like? Message-ID: <E15x7zW-0005KU-00@thunder5.cwihosting.com> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD><TITLE>Gary M. Gordon - FREE Website Enhancement Promotional Offer

          FREE WEBSITE ENHANCEMENT OFFER
                  yes, ... absolutely FREE
!

                (No contracts!   No commitments!   No cost!)
          - Links to sample enhancements are provided below. -

As a way to introduce our company to you, we are going to give
you an enhancement that you can add to your website ............
                                          absolutely FREE!

===================================================
 
   Just select from one of our FREE website enhancement features
   that are listed below.  There are 'No contracts required!' ..
There are ...
  • No commitments!
    No costs!
    and ...
    we will also set everything up ... for FREE!
   Let me introduce myself ...
 
   My name is Gary Gordon. I am the owner of Gary M. Gordon, LLC
   a WEB DEVELOPMENT COMPANY which provides complete solutions
   for the needs of small to large businesses. (No project is ever to
   small or to large.)  If you need a 'fix' or 'enhancement' added to
   a current website ... that's perfect.  If you need to have a new
   website developed from scratch ... that's great.   We do it all!
 
 
   FREE WEBSITE ENHANCEMENTS YOU CAN CHOOSE FROM:
 
   (Simply click on the 'http:// link' provided below the title of
   each item to view just a sample of the FREE enhancement.)
 
   1)  FREE 'Macromedia Flash (.SWF FORMAT) Animation'
http://www.garymgordon.com/flash_samples/demo/logo_flash_sample.html
Simply provide us with any text, logo and/or photo(s) that you would
like to have animated and developed as a FLASH (.SWF) ANIMATION.

   2)  FREE 'Cursor Trailer - Animated Clock (Javascript)'
http://www.garymgordon.com/javascript_samples/clock_cursor/index.html
We will insert and set up this attractive and eye catching feature to
work on any webpage of your website.

   3)  FREE 'your choice of any of the following Javascripts'
We will insert and set them up to work in any webpage on your website'.
 
       a)    Page Content Management that automatically allows content
       to be displayed on a page - from and through a specified date, then
       it is automatically removed from the page.
http://www.garymgordon.com/javascript_samples/content_mgmt/index.html
 
       b)    Auto Scroller for Text and Images.  This provides a
       scrolling message that can include text and images (with links
       to other pages or websites).
http://www.garymgordon.com/javascript_samples/scroller_box/index.html
 
       c)    Navigational Menu System that allows you to utilize a drop
       down menu that lists any number of pages, websites, etc. It is
       a convenient and space saving way to add lots of links within
       a small place on a webpage.
http://www.garymgordon.com/javascript_samples/dropdownmenu/index.html
 

Now ... you can choose from any of the above website enhancements
absolutely FREE!
 
Then, simply contact us and we will set everything up for you - NO CHARGE!
 
(This is simply our way of introducing our company to you.)
 
E-mail us at:   webmaster@garymgordon.com
or
Phone us at:    1-856-482-8320  (New Jersey, USA)

===================================================
 
              To request your FREE website enhancement,
              please include the following two lines of
              information in the BODY of your reply email:
 
                  FREE WEBSITE ENHANCEMENT OFFER
                                      WE-149-359-1001
 
                  Also provide us with the following:
 
                  1)  Your company name and address.
                  2)  Your first and last name.
                  3)  Your title/position with the company.
                  4)  Your telephone number - and the best
                        time to reach you by phone.
                  5)  Your website URL (if you have one).
 
                  We will email or call you back shortly to discuss
                  the free enhancement of your choice.
 
===================================================
 
    OUR CORPORATE INFORMATION:
 
    Gary M. Gordon, LLC
    - A Global Web Development Corporation
    421 Jamaica Drive
    Cherry Hill, New Jersey  08002
 
    (Available -  7 days a week.)
 
         E-mail ::  webmaster@garymgordon.com
         Phone  ::  856-482-8320
         Fax    ::  801-858-4271
 

    Background Information of GARY M. GORDON (Owner):
 
    Certified Senior Web Developer since 1996
    Certified Web Master Instructor since 1999
    20+ years experience in Sales/Marketing/Graphic Design
    and Development
 
  
    Additional Comments:
 
    Gary M. Gordon, LLC (Web Development Services) was created
    in an effort to provide quality 'web development' work on a
    world-wide scale through the joint efforts of a comprehensive
    and world-wide network (that includes a selected group of
    professional and certified application programmers, website
    developers, graphic designers, etc. - from the USA, Canada,
    India, Romania, Japan, Australia, and others).
 
                    ALL OF OUR WORK IS PROVIDED
              WITH A 100% SATISFACTION GUARANTEE!
 
    So, if you're not satisfied with our work, ... you don't pay.
    It's as simple as that!
 
    Please feel free to visit our website or email us at your
    convenience, and we will be happy to help you in any way
    possible.
 

    * Certain restrictions or requirements may apply to all work
    requests, free offers, etc.  Please ask for complete details.
 
    Free offers are also limited to one per website domain and/or
    company.  Gary M. Gordon, LLC reserves the right to discontinue,
    change, or modify this free offer at any time without notice.
 



If your browser doesn't support the display of HTML, you can access the same information as shown above by following the link to take advange of our Free Website Enhancement Offer at: http://www.garymgordon.com/services.html (then, on this page, look for the link that says "Free Current Promotional Offer).


-------------------------------------------------------------------------------------
If you have joined Gary M. Gordon, LLC by accident or someone else has joined you without your permission,
or if you ever want to remove yourself from Gary M. Gordon, LLC, simply visit:
http://www.garymgordon.com/easylist/easylist.cgi?action=unsubscribe&submitemail=tutor@python.org
and you will be automatically removed.

From dyoo@hkn.eecs.berkeley.edu Fri Oct 26 16:59:19 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 26 Oct 2001 08:59:19 -0700 (PDT) Subject: [Tutor] Why different behaviours? In-Reply-To: Message-ID: On Fri, 26 Oct 2001, Danny Kohn wrote: > Why does: > import string, sys > f=open('d:/Dokument/Programprojekt/pythonworks/projects/H2/Lexicon.txt', 'r') > line = f.readline() > print line > > and: > > import string, sys > f=open('d:/Dokument/Programprojekt/pythonworks/projects/H2/Lexicon.txt', 'r') > for line in f.readline(): > print line The variable naming in your second version might be obscuring an issue: > for line in f.readline(): > print line In this case, we're asking Python to do a for loop along every thing in an f.readline(). In that case, we're going to go along every character of that read line, so the loop might be better written as: ## for character in f.readline(): print line ### Also, Python's "print" statement will automatically put a newline, unless we place a trailing comma. We can see this from this interpreter session: ### >>> print "abc" abc >>> for letter in "abc": ... print letter ... a b c >>> for letter in "abc": ... print letter, ... a b c ### It sounds like you've had some programming experience already, so I don't have qualms about recommending the official Python library: http://www.python.org/doc/current/tut/tut.html The section on "Fancier Output Formatting" should give you more control over how your programs print things. > Also, what would be the way to read line after line until end of file. > How to detect end of file when reading a sequential file this way? According to: http://www.python.org/doc/current/tut/node9.html#SECTION009200000000000000000 """f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn't end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline.""" If you have more questions, please feel free to ask. Good luck! From dsh8290@rit.edu Fri Oct 26 17:07:45 2001 From: dsh8290@rit.edu (dman) Date: Fri, 26 Oct 2001 12:07:45 -0400 Subject: [Tutor] Learning about other languages by using Python [S In-Reply-To: <01102515555601.08643@tygesen>; from rufmetal@home.com on Thu, Oct 25, 2001 at 03:55:56PM -0500 References: <20011025120403.A29392@harmony.cs.rit.edu> <01102515555601.08643@tygesen> Message-ID: <20011026120745.A7783@harmony.cs.rit.edu> On Thu, Oct 25, 2001 at 03:55:56PM -0500, Chris Keelan wrote: | -----BEGIN PGP SIGNED MESSAGE----- | Hash: SHA1 | | On Thursday 25 October 2001 11:04, dman wrote: | | > There's the R5RS document. It is the standard that defines the core | > of scheme. It stands for Revised Revised Revised Revised Revised | > Reference on Scheme (or something like that). It is not a tutorial in | > any way. It also shows that pure scheme isn't really useful for | > real-world programming, but I know that the Guile people have added | > lots to the library to make it useful. ... | This is an amzing site, if you're new to programming. While I agree with dman | that Python might be more useful for 'real world' stuff, Scheme is an Upon reading this, my statement could sound like I'm condemming Scheme. I didn't intend to, and I think Scheme is pretty neat, especially the tail-recursion optimization. (I've heard of lisp beating fortran in speed of number crunching!) -D From dsh8290@rit.edu Fri Oct 26 17:10:17 2001 From: dsh8290@rit.edu (dman) Date: Fri, 26 Oct 2001 12:10:17 -0400 Subject: [Tutor] [OT] Bay PIGgies hijacked? In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Thu, Oct 25, 2001 at 02:52:55PM -0700 References: <20011025110234.A29346@harmony.cs.rit.edu> Message-ID: <20011026121016.B7783@harmony.cs.rit.edu> On Thu, Oct 25, 2001 at 02:52:55PM -0700, Danny Yoo wrote: | On Thu, 25 Oct 2001, dman wrote: | | > I just tried to follow a link to an intro on using libglade with | > python on www.baypiggies.org, but ended up at a porn site >8^p. Did | > someone screw up the DNS records? Is there a way I can get to the | > site (is it a static IP that you can share)? | | Hi dman, | | Yeah, we know about this. The domain got hijacked before Baypiggies was | able to renew the record. That's too bad :-(. | As a result, I think Baypiggies is trying to redirect the baypiggies.org | web site to: | | http://deirdre.org/baypiggies/ | | It's not up yet, but it'll be up soon. In the meantime, if you see any | links to http://baypiggies.org on a website, please notify the webmaster | to link Baypiggies to http://deirdre.org/baypiggies/, so that we can route | around the damage. Sure. The link I found was part of a (at least) year-old news post on gnome.org. -D From dyoo@hkn.eecs.berkeley.edu Fri Oct 26 18:24:05 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 26 Oct 2001 10:24:05 -0700 (PDT) Subject: [Tutor] Why different behaviours? In-Reply-To: Message-ID: On Fri, 26 Oct 2001, Danny Yoo wrote: > On Fri, 26 Oct 2001, Danny Kohn wrote: > > > Why does: > > import string, sys > > f=open('d:/Dokument/Programprojekt/pythonworks/projects/H2/Lexicon.txt', 'r') > > line = f.readline() > > print line > > > > and: > > > > import string, sys > > f=open('d:/Dokument/Programprojekt/pythonworks/projects/H2/Lexicon.txt', 'r') > > for line in f.readline(): > > print line > > > The variable naming in your second version might be obscuring an issue: > > > for line in f.readline(): > > print line > > In this case, we're asking Python to do a for loop along every thing in an > f.readline(). In that case, we're going to go along every character of > that read line, so the loop might be better written as: > > ## > for character in f.readline(): > print line > ### Err... I meant: ### for character in f.readline(): print character ### Sorry, my brain hiccupped. *grin* From dyoo@hkn.eecs.berkeley.edu Fri Oct 26 19:43:51 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 26 Oct 2001 11:43:51 -0700 (PDT) Subject: [Tutor] TypeError: __str__ returned non-string (type DbiRaw) In-Reply-To: Message-ID: On Tue, 23 Oct 2001, Troy Sorzano wrote: > Hi All, > > I am a python newbie and having a little problem with dbiRaw. I am > connecting via ODBC to a MS SQL 2000 database. The 3 column in the > select statement is a BLOB that actually contains text. I want to > convert that BLOB into a string but I can not figure out how to. The > error I get is "TypeError: __str__ returned non-string (type DbiRaw)" Dear Troy, Hi, just checking up on your question; it looks like you haven't gotten an answer yet. The error message you're getting seems really weird; the __str__ method of any Python object should always return some sort of string, but the error message is saying otherwise. I have no clue about this either, and can't investigate this since I don't have a Windows system handy. You might want to try asking your question to the Python-win32 mailing list: http://aspn.activestate.com/ASPN/Mail/About/Python-win32/ They should have people there who can better look into this problem. Hope you can find answers to this problem. Good luck! From danny.kohn@systematik.se Fri Oct 26 21:11:48 2001 From: danny.kohn@systematik.se (Danny Kohn) Date: Fri, 26 Oct 2001 22:11:48 +0200 Subject: SV: [Tutor] Why different behaviours? In-Reply-To: Message-ID: Thanks everybody for the answers. It works now. Danny, the problem is not the print formatting in gerenal although it = might have been. What bugs me is why the print statement in the first = example is not printing out one character per line (as there is no comma = last!). It seems to me that there is something more fundamental I have = not grasped yet. Why is there a difference between when a string is = printed and when it is used in a for loop as index? In Basic for example I can be certain that what I see when I print is = what I get internaly. Here it seems that I get one thing when I print it = and another thing when I try to use it internally in code. Either the = result of f.readline is a character and so each character should print = out on a separate line or it is not a character and so it should be used = as a line in a for loop. /Danny | -----Ursprungligt meddelande----- | Fran: tutor-admin@python.org [mailto:tutor-admin@python.org]For Danny | Yoo | Skickat: den 26 oktober 2001 17:59 | > Why does: | > import string, sys | >=20 | f=3Dopen('d:/Dokument/Programprojekt/pythonworks/projects/H2/Lexicon | .txt', 'r') | > line =3D f.readline() | > print line | >=20 | > and: | >=20 | > import string, sys | >=20 | f=3Dopen('d:/Dokument/Programprojekt/pythonworks/projects/H2/Lexicon | .txt', 'r') | > for line in f.readline(): | > print line |=20 |=20 | The variable naming in your second version might be obscuring an = issue: |=20 | > for line in f.readline(): | > print line |=20 | In this case, we're asking Python to do a for loop along every thing = in an | f.readline(). In that case, we're going to go along every character = of | that read line, so the loop might be better written as: |=20 | ## | for character in f.readline(): | print line | ### |=20 |=20 | Also, Python's "print" statement will automatically put a newline, = unless | we place a trailing comma. We can see this from this interpreter = session: |=20 | ### | >>> print "abc" | abc | >>> for letter in "abc": | ... print letter | ... | a | b | c | >>> for letter in "abc": | ... print letter, | ... | a b c | ### From kromag@nsacom.net Fri Oct 26 23:39:11 2001 From: kromag@nsacom.net (kromag@nsacom.net) Date: Fri, 26 Oct 2001 15:39:11 -0700 (PDT) Subject: [Tutor] Pretty and invisible Message-ID: <200110262239.f9QMdBY18168@pop.nsacom.net> I would like to do two things with the following script: First, I believe it could be made much simpler and prettier: May I have suggestions? I found an example of a phone book script in "Learning Python" that is similar, I will begin there, but I get easily lost in inheritance (judging from my last post, I would get lost on the way to the bathroom....) :-) Second, I would like to either not echo or obscure the password raw_input(). I have looked through Learing Python and around the web for examples: I am probably missing it! **ALERT**ALERT**ALERT**ALERT**ALERT**ALERT** Mail from this account is sent from a webmail program called TWIG. TWIG will strip the leading /'s from open('//tmp//filename') and the like. Thanks! _________________login.py__________________ import cPickle import string import time import sys import os '''login checks a pickled dictionary for usernames/passwords, creates new u/p's and rejects mistyped passwords''' #open password file, grab the dictionary of usernames and passwords, then close it. passwd=open('\tmp\passwd','r') passlist=cPickle.load(passwd) passwd.close() #untrused username password combination uname=raw_input('Enter Player Name: ') password=raw_input('Enter Password: ') untrusted={uname: password} #check and see if the existing passlist has the username check=passlist.has_key(uname) #if there is no existing key in passlist that matches uname, add it and a password. if check==0: print 'Name not found. Adding.' password=raw_input('Enter new Password for '+uname+': ') passlist[uname]=password passwd=open('\tmp\passwd','w') cPickle.dump(passlist, passwd) passwd.close() print 'user and password added' os.system('\windows\command\edit.com ' +uname) sys.exit() #if the values for the passlist key match the value for untrusted key, start app. elif passlist[uname] == untrusted[uname]: print 'user + pass ok ' os.system('\windows\command\edit.com ' +uname) sys.exit() #if the values for the passlist key do not match the value for the untrusted key, kill script elif passlist[uname] != untrusted[uname]: print 'Either the user already exists, or you mistyped the password, sorry!' #Snooze for a few secs before the connection drops... time.sleep(3) sys.exit('Access Denied') #get the hell out of here, regardless! :-) else: sys.exit('Error') _________________end login.py____________________ Thanks all! From dsh8290@rit.edu Fri Oct 26 21:39:01 2001 From: dsh8290@rit.edu (dman) Date: Fri, 26 Oct 2001 16:39:01 -0400 Subject: [Tutor] Pretty and invisible In-Reply-To: <200110262239.f9QMdBY18168@pop.nsacom.net>; from kromag@nsacom.net on Fri, Oct 26, 2001 at 03:39:11PM -0700 References: <200110262239.f9QMdBY18168@pop.nsacom.net> Message-ID: <20011026163901.A8556@harmony.cs.rit.edu> On Fri, Oct 26, 2001 at 03:39:11PM -0700, kromag@nsacom.net wrote: | I would like to do two things with the following script: | | First, I believe it could be made much simpler and prettier: May I have | suggestions? | | I found an example of a phone book script in "Learning Python" that is | similar, I will begin there, but I get easily lost in inheritance (judging | from my last post, I would get lost on the way to the bathroom....) :-) For inheritance, remember the "is-a" relationship. If I have : class Vehicle : pass class Car( Vehicle ) : pass then a Car instance is-a Vehicle instance. That is, a Car can do everything a Vehicle can do, but maybe with some extra functionality or in a particular way. | Second, I would like to either not echo or obscure the password raw_input(). Perhaps you can read a character synchronously from the input, then immediately write out a backspace character and an asterix. I remember a friend of mine trying to do that in a little java program once, but having some difficulty do to timing and stuff. Another way would be to access the terminal directly (I think this is what, ex, ssh does) but that limits portability. Perhaps ncurses has "password input" functionality? Many GUI toolkits have password entry boxes. HTH, -D From tonycervone@netzero.net Fri Oct 26 21:32:31 2001 From: tonycervone@netzero.net (tonycervone) Date: Fri, 26 Oct 2001 16:32:31 -0400 Subject: [Tutor] null string Message-ID: <001101c15e5d$572e34e0$778df4d1@w9y5d5> This is a multi-part message in MIME format. ------=_NextPart_000_000E_01C15E3B.CEEE7520 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable How does one check for a null string in an if condition? thanks. tony ------=_NextPart_000_000E_01C15E3B.CEEE7520 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
How does one check for a null string in = an if=20 condition? thanks. tony
------=_NextPart_000_000E_01C15E3B.CEEE7520-- ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From boud@valdyas.org Fri Oct 26 21:54:23 2001 From: boud@valdyas.org (Boudewijn Rempt) Date: Fri, 26 Oct 2001 22:54:23 +0200 Subject: [Tutor] null string In-Reply-To: <001101c15e5d$572e34e0$778df4d1@w9y5d5> References: <001101c15e5d$572e34e0$778df4d1@w9y5d5> Message-ID: <200110262054.f9QKsQp16864@calcifer.valdyas.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Friday 26 October 2001 22:32, tonycervone wrote: > How does one check for a null string in an if condition? thanks. tony Depends on what you think 'null' should be - either compare it to the None object, or to the empty string: if s =3D=3D None or s =3D=3D "": =09print "This might be considered a null string" This contrasts with systems like the Oracle database, where a null value can have a type. A real Python null is always None. - --=20 Boudewijn Rempt | http://www.valdyas.org -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE72c2AN8fj6DnPxOgRAhh0AJwJWG9PBT7ZS42FxUEgAAqENfIUjwCgtmcs HK/u7T2D7WnQ7Z8Etr3vtWc=3D =3DjBCx -----END PGP SIGNATURE----- From dyoo@hkn.eecs.berkeley.edu Fri Oct 26 22:10:02 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 26 Oct 2001 14:10:02 -0700 (PDT) Subject: SV: [Tutor] Why different behaviours? In-Reply-To: Message-ID: On Fri, 26 Oct 2001, Danny Kohn wrote: > Danny, the problem is not the print formatting in gerenal although it > might have been. What bugs me is why the print statement in the first > example is not printing out one character per line (as there is no > comma last!). It seems to me that there is something more fundamental > I have not grasped yet. Why is there a difference between when a > string is printed and when it is used in a for loop as index? The difference is that Python knows how to print "sequences" all at once: ### >>> print [1, 2, 3, 4] [1, 2, 3, 4] >>> print "1234" 1234 ### One of the unique features of the Python 'for' loop is that it works on a "sequence". I'm putting the word "sequence" in quotes, because there are several things in Python that look like sequences: ### >>> for x in ('larry', 'curly', 'moe'): ... print 'yuk yuk', x ... yuk yuk larry yuk yuk curly yuk yuk moe >>> for x in ['bill', 'ted']: ... print "excellent", x ... excellent bill excellent ted >>> for letter in "bee": ... print 'I spell', letter ... I spell b I spell e I spell e ### > In Basic for example I can be certain that what I see when I print is > what I get internaly. Here it seems that I get one thing when I print > it and another thing when I try to use it internally in code. Either > the result of f.readline is a character and so each character should > print out on a separate line or it is not a character and so it should > be used as a line in a for loop. Using a for loop causes Python to look at each element in the "sequence" individually, so it adds an extra layer between the Thing that we're looking at, and the process of printing that Thing. Instead of calling "print" on the whole sequence, ### print sequence ### we now tell Python to "print" every piece, individually. ### for piece in sequence: print piece ### If it helps, it might help to boil: ### for line in f.readline(): print line ### into a concoction that's almost equivalent, but a little more bland and wordier: ### some_line = f.readline() ## f.readline() sucks in an entire line. for character in some_line: ## I renamed "line" to character. print character ### That is, the for loop above is only working on a single line, iterating over every character of some_line. Also, note that it only calls f.readline() once. [Note: I must be honest: this is only a simplified model of how the for loop does its work. As you learn Python, you'll make more accurate models of what's happening.] Here are some examples you can try out: ### for thing in ['last', 'best'] + ['hope', 'for', 'peace']: print "Babylon 5: ", thing for number in range(5): print number, number**2, number**3 ### and of course, you should make up your own. Using the interpreter is invaluable, as it allows you to directly experiment with the for loop. Please continue to ask questions on this; we'll do our best to make sure this makes sense eventually... *grin* From dyoo@hkn.eecs.berkeley.edu Fri Oct 26 22:15:06 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 26 Oct 2001 14:15:06 -0700 (PDT) Subject: [Tutor] null string In-Reply-To: <200110262054.f9QKsQp16864@calcifer.valdyas.org> Message-ID: On Fri, 26 Oct 2001, Boudewijn Rempt wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > On Friday 26 October 2001 22:32, tonycervone wrote: > > How does one check for a null string in an if condition? thanks. tony > > Depends on what you think 'null' should be - either compare > it to the None object, or to the empty string: > > if s == None or s == "": > print "This might be considered a null string" > > This contrasts with systems like the Oracle database, > where a null value can have a type. A real Python null > is always None. Also, it helps to see what Python considers is a "true" value: ### def isTrue(x): if x: return 1 return 0 ### Ok, it's a silly looking definition, but it's useful in experimenting with this sort of stuff: ### >>> isTrue(42) 1 >>> isTrue("false") ## Sorry, I couldn't resist... *grin* 1 >>> isTrue(None) 0 >>> isTrue("") 0 >>> isTrue("0") ## Here's where Perl and Python diverge... 1 ### Hope this helps! From lkvam@venix.com Fri Oct 26 22:20:15 2001 From: lkvam@venix.com (Lloyd Kvam) Date: Fri, 26 Oct 2001 17:20:15 -0400 Subject: SV: [Tutor] Why different behaviours? References: Message-ID: <3BD9D38F.65B98B72@venix.com> (Danny Yoo, I hope you don't mind my sticking in my two cents here) A string can be handled as a unit or as a sequence of characters. This is meant as a convenience. For those cases where you want to deal with the characters that make up the string you would use the sequence oriented statements and functions. For dealing with the string as a whole, use the "field" oriented statements. The old-style Dartmouth Basic did not have any sequence abilities built in. Microsoft's Visual Basic does, but they will not work on strings. From VB's point of view, a string is not a collection. This forces you to use the MID, LEFT, and RIGHT functions to work on the characters in a string. Python, by allowing you to view a string as a collection of characters AND as a unit, is really making your life easier. The same commands that let you pull a list apart also work on strings. You do not have to use special functions to access the string as a collection. Some python code that may help: >>> s = 'this is a string' >>> slist = map(None, s) # turn s into a list of characters >>> slist ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g'] >>> s[3:11] 's is a s' >>> slist[3:11] ['s', ' ', 'i', 's', ' ', 'a', ' ', 's'] Danny Kohn wrote: > > Thanks everybody for the answers. It works now. > > Danny, the problem is not the print formatting in gerenal although it might have been. What bugs me is why the print statement in the first example is not printing out one character per line (as there is no comma last!). It seems to me that there is something more fundamental I have not grasped yet. Why is there a difference between when a string is printed and when it is used in a for loop as index? > > In Basic for example I can be certain that what I see when I print is what I get internaly. Here it seems that I get one thing when I print it and another thing when I try to use it internally in code. Either the result of f.readline is a character and so each character should print out on a separate line or it is not a character and so it should be used as a line in a for loop. > > /Danny > > | -----Ursprungligt meddelande----- > | Fran: tutor-admin@python.org [mailto:tutor-admin@python.org]For Danny > | Yoo > | Skickat: den 26 oktober 2001 17:59 > > | > Why does: > | > import string, sys > | > > | f=open('d:/Dokument/Programprojekt/pythonworks/projects/H2/Lexicon > | .txt', 'r') > | > line = f.readline() > | > print line > | > > | > and: > | > > | > import string, sys > | > > | f=open('d:/Dokument/Programprojekt/pythonworks/projects/H2/Lexicon > | .txt', 'r') > | > for line in f.readline(): > | > print line > | > | > | The variable naming in your second version might be obscuring an issue: > | > | > for line in f.readline(): > | > print line > | > | In this case, we're asking Python to do a for loop along every thing in an > | f.readline(). In that case, we're going to go along every character of > | that read line, so the loop might be better written as: > | > | ## > | for character in f.readline(): > | print line > | ### > | > | > | Also, Python's "print" statement will automatically put a newline, unless > | we place a trailing comma. We can see this from this interpreter session: > | > | ### > | >>> print "abc" > | abc > | >>> for letter in "abc": > | ... print letter > | ... > | a > | b > | c > | >>> for letter in "abc": > | ... print letter, > | ... > | a b c > | ### > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From dyoo@hkn.eecs.berkeley.edu Fri Oct 26 22:22:32 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 26 Oct 2001 14:22:32 -0700 (PDT) Subject: SV: [Tutor] Why different behaviours? In-Reply-To: <3BD9D38F.65B98B72@venix.com> Message-ID: On Fri, 26 Oct 2001, Lloyd Kvam wrote: > (Danny Yoo, I hope you don't mind my sticking in my two cents here) Of course I don't mind: that's exactly what a public forum is for. *grin* Thank you! From lkvam@venix.com Fri Oct 26 23:37:56 2001 From: lkvam@venix.com (Lloyd Kvam) Date: Fri, 26 Oct 2001 18:37:56 -0400 Subject: [Tutor] new Linux Installation Message-ID: <3BD9E5C4.2D479D3F@venix.com> I am setting up a new Linux server so that I can use Python scripts for CGI processing. I decided to also include a GUI interface. It is time to join the 21st century. I have a choice of Gnome and KDE. Does it matter? Presumably I will be using Tkinter for Python based GUI programming. Does Tkinter care? -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From kalle@gnupung.net Fri Oct 26 23:55:05 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Sat, 27 Oct 2001 00:55:05 +0200 Subject: [Tutor] new Linux Installation In-Reply-To: <3BD9E5C4.2D479D3F@venix.com> References: <3BD9E5C4.2D479D3F@venix.com> Message-ID: <20011027005504.B24500@sandra.lysator.liu.se> [Lloyd Kvam] > I have a choice of Gnome and KDE. Does it matter? Presumably I will be > using Tkinter for Python based GUI programming. Does Tkinter care? No, it doesn't matter, it's only a matter of taste. Tkinter doesn't care. Peace, Kalle -- [ Thought control, brought to you by the WIPO! ] [ http://anti-dmca.org/ http://eurorights.org/ ] From ak@silmarill.org Sat Oct 27 01:46:43 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Fri, 26 Oct 2001 20:46:43 -0400 Subject: [Tutor] new Linux Installation In-Reply-To: <3BD9E5C4.2D479D3F@venix.com> References: <3BD9E5C4.2D479D3F@venix.com> Message-ID: <20011026204642.A12824@sill.silmarill.org> On Fri, Oct 26, 2001 at 06:37:56PM -0400, Lloyd Kvam wrote: > I am setting up a new Linux server so that I can use Python scripts for CGI processing. I decided to also include a GUI interface. It is time to join the 21st century. > > I have a choice of Gnome and KDE. Does it matter? Presumably I will be using Tkinter for Python based GUI programming. Does Tkinter care? You don't have to choose either. There's a plenty of window managers. Most well known are WindowMaker, Enlightenment, blackbox, icewm. The idea behind both gnome and kde is to have an integrated environment like windows so that it's easy for newbies to switch. The tradeoff is that they're slower and take more memory. As far as python's concerned, you can run anything. > > -- > Lloyd Kvam > Venix Corp. > 1 Court Street, Suite 378 > Lebanon, NH 03766-1358 > > voice: 603-443-6155 > fax: 801-459-9582 > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From pythonpython@hotmail.com Sat Oct 27 02:43:14 2001 From: pythonpython@hotmail.com (Hy Python) Date: Sat, 27 Oct 2001 01:43:14 +0000 Subject: [Tutor] codecs and unicodedata Message-ID: Could you tell me where I can find some GOOD tutorials on using codecs and unicodedata modules? The tutorials on Python.org regarding these two modules are not detailed enough for me to understand them... Thank you for your help. Hy _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp From dsh8290@rit.edu Sat Oct 27 04:00:57 2001 From: dsh8290@rit.edu (dman) Date: Fri, 26 Oct 2001 23:00:57 -0400 Subject: [Tutor] new Linux Installation In-Reply-To: <3BD9E5C4.2D479D3F@venix.com>; from lkvam@venix.com on Fri, Oct 26, 2001 at 06:37:56PM -0400 References: <3BD9E5C4.2D479D3F@venix.com> Message-ID: <20011026230056.A9839@harmony.cs.rit.edu> On Fri, Oct 26, 2001 at 06:37:56PM -0400, Lloyd Kvam wrote: | I am setting up a new Linux server so that I can use Python scripts | for CGI processing. I decided to also include a GUI interface. It | is time to join the 21st century. | | I have a choice of Gnome and KDE. Does it matter? Presumably I | will be using Tkinter for Python based GUI programming. Does | Tkinter care? GNOME is better . Well, that's my opinion -- I just like the way it looks better. I use sawfish as the window manager with GNOME. As far as python and tkinter are concerned, all you need is an X display. Having a window manager to manage that display makes using X much much more useful and comfortable, but isn't essential. There are many window managers available, Kalle mentioned some of them. GNOME and KDE are desktop environments. That is, they provide a number of useful services for applications (to reduce reinvention of the wheel) and a common look-n-feel. Both desktops have a panel with a menus, pager, launchers, and other applets. Try both desktop environments, try different window managers, try a wm without a desktop, see which setup you like best. You can always remove the unwanted one later. -D From joejava@dragoncat.net Sat Oct 27 05:56:54 2001 From: joejava@dragoncat.net (Joel Ricker) Date: Sat, 27 Oct 2001 00:56:54 -0400 Subject: [Tutor] Python performance on Windows system Message-ID: <002701c15ea3$cdb33ac0$98a0d6d1@joeltklrijxxms> This is a multi-part message in MIME format. ------=_NextPart_000_0024_01C15E82.45BAE440 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi all, I've been away from Python for a little while and so to stretch my = programming legs a little bit, I've been working on a script to generate = prime numbers. I've used a sieve algorithm and originally a list of = numbers in an array and have reworked it to use a text file in the same = way. I've noticed when working with big numbers, say finding all prime = numbers between 1 and 5 million, my system becomes a little less = responsive. It was real bad when I used a large array since sometimes = the memory used by python would run into the 100 meg range but since = I've switched to using a file it has improved alot but its still there.=20 Basically what happens is while the script is running, other windows = are a little slow to appear and starting new programs or closing windows = takes several seconds to hapen. I'm running Windows 2000, with a 750 = mhz processor and 128megs of memory. What is odd though is that using = Task Manager, I see that Python isn't using that much CPU -- only 1 or 2 = percent at the most and very little memory -- about 520k. =20 Is it all the disk writes that is slowing things down? Anything I can = do to my code to help things along? Or anything I can do to the python = interpreter itself? Below is the main part of the code that is doing = most of the work in the script. primein.txt is a text file containing a = list of numbers between 0 and the max number to search to. Thanks Joel f =3D open('primein.txt','r+') =20 x =3D 2 endsqrt =3D math.floor(math.sqrt(end)) while x <=3D endsqrt: print x =20 for y in xrange(2, end/x+1): f.seek(x * y * 12) f.write('%10d\n' % 0) f.flush() f.seek(x * 12 + 12) while 1: x =3D f.readline() if int(x) > 0: x =3D int(x) break =20 ------=_NextPart_000_0024_01C15E82.45BAE440 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi all,
 
I've been away from Python for  a = little while=20 and so to stretch my programming legs a little bit, I've been working on = a=20 script to generate prime numbers.  I've used a sieve algorithm and=20 originally a list of numbers in an array and have reworked it to use a = text file=20 in the same way. I've noticed when working with big numbers, say finding = all=20 prime numbers between 1 and 5 million, my system becomes a little less=20 responsive.  It was real bad when I used a large array since = sometimes the=20 memory used by python would run into the 100 meg range but since = I've=20 switched to using a file it has improved alot but its still=20 there. 
 
 Basically what happens is while = the script is=20 running, other windows are a little slow to appear and starting new = programs or=20 closing windows takes several seconds to hapen.  I'm running = Windows 2000,=20 with a 750 mhz processor and 128megs of memory.  What is odd though = is that=20 using Task Manager, I see that Python isn't using that much CPU -- only = 1 or 2=20 percent at the most and very little memory -- about 520k.  =
 
Is it all the disk writes that is = slowing things=20 down?  Anything I can do to my code to help things along?  Or = anything=20 I can do to the python interpreter itself?  Below is the main = part of=20 the code that is doing most of the work in the script.  primein.txt = is a=20 text file containing a list of numbers between 0 and the max number to = search=20 to.
 
Thanks
Joel
 
    f =3D=20 open('primein.txt','r+') 
    x =3D=20 2
    endsqrt =3D=20 math.floor(math.sqrt(end))
    while x <=3D=20 endsqrt:
        print=20 x       =20
        for y in xrange(2,=20 end/x+1):
          =  =20 f.seek(x * y *=20 12)
           = =20 f.write('%10d\n' % 0)
       =20 f.flush()
        f.seek(x * 12 +=20 12)
        while=20 1:
            = x =3D=20 f.readline()
         &nb= sp; =20 if int(x) >=20 0:
           &= nbsp;   =20 x =3D=20 int(x)
          &nb= sp;    =20 break     
------=_NextPart_000_0024_01C15E82.45BAE440-- From boud@valdyas.org Sat Oct 27 09:42:09 2001 From: boud@valdyas.org (Boudewijn Rempt) Date: Sat, 27 Oct 2001 10:42:09 +0200 Subject: [Tutor] codecs and unicodedata In-Reply-To: References: Message-ID: <200110270842.f9R8gAJ04048@calcifer.valdyas.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Saturday 27 October 2001 03:43, Hy Python wrote: > Could you tell me where I can find some GOOD tutorials on using codecs = and > unicodedata modules? The tutorials on Python.org regarding these two > modules are not detailed enough for me to understand them... > I went rather over the top explaining Unicode in=20 http://stage.linuxports.com/pyqt/c1624.htm Not all the details, but most of the background. As far as PyQt is concer= ned, the last section is obsoleted by recent developments, though. - --=20 Boudewijn Rempt | http://www.valdyas.org -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE72nNhN8fj6DnPxOgRAo8LAKCXTm2r48VMFjalD3pGiN0xYS2QkACgqnWL piK3ATCpxT5jVTSTNhjrXvA=3D =3DcjKf -----END PGP SIGNATURE----- From tonycervone@netzero.net Sat Oct 27 11:54:43 2001 From: tonycervone@netzero.net (tonycervone) Date: Sat, 27 Oct 2001 06:54:43 -0400 Subject: [Tutor] More help needed in sorting files and strings Message-ID: <000a01c15ed5$ca3991a0$d280f4d1@w9y5d5> This is a multi-part message in MIME format. ------=_NextPart_000_0007_01C15EB4.4202F9A0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi all.=20 I have been using this code to read weather reports and to print only = the first two stations symbols in the file: inp =3Dopen("Metar\Infometar.txt") lines =3D inp.readlines() Depart =3D lines[1].split()[0] Destin =3D lines[4].split()[0] Destin1 =3D lines[5].split()[0] Print Depart+" "+Destin+" "+Destin1 This code works fine until it finds an empty line and then I get an out = of range error. Here's why: 2001/10/23 21:18 KPVD 232118Z AUTO 22014KT 3/4SM +TSRA BKN021 OVC033 20/14 A2937 RMK AO2 2001/10/23 21:18 KLGA 232118Z AUTO 23008KT 6SM -SHRA BKN012 18/17 A2962 RMK AO2 2001/10/23 21:18 KBDL 232118Z AUTO 01012KT 6SM RA OVC050 14/05 A2965 RMK AO2 In the example above, the Depart =3D lines[1].split()[0] always works = because all files start that way. The code will print out KPVD = 2001/10/23 KLGA. This is perfect if all reports contained the same = number of lines. If, however, another report has all the information = contained in two lines instead ot three, the Destin1 =3D = lines[5].split()[0] will give me an out of range error, and the Destin = =3D lines[4].split()[0] will give me 2001/10/23 instead of KLGA. So this is where I get lost. It would seem that a simple" if condition" = checking for either a null string or something other than a null would = do the trick. i would then replace the actual numbers in the bracket s = with variables that would point to the correct line. The problem is that = I cannot use the line[].split()[] statement to do the checking without = first getting the "out of range error" in an if condition. What other = "simple" routine can I use to ensure avoidance of that error? thank you. = tony ------=_NextPart_000_0007_01C15EB4.4202F9A0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi all.
 
I have been using this code to read = weather reports=20 and to print only the first two stations symbols in the = file:
       inp=20 =3Dopen("Metar\Infometar.txt")
       = lines =3D=20 inp.readlines()
       Depart =3D=20 lines[1].split()[0]
       Destin =3D=20 lines[4].split()[0]
       Destin1 =3D=20 lines[5].split()[0]
       Print = Depart+"=20 "+Destin+" "+Destin1
 
This code  works fine until it = finds an empty=20 line and then I get an out of range error. Here's why:
 
2001/10/23 21:18
KPVD 232118Z AUTO = 22014KT 3/4SM=20 +TSRA BKN021 OVC033 20/14=20 A2937
          RMK = AO2
 
2001/10/23 21:18
KLGA 232118Z AUTO = 23008KT 6SM=20 -SHRA BKN012 18/17 A2962 = RMK
        =20 AO2
 
2001/10/23 21:18
KBDL 232118Z AUTO = 01012KT 6SM=20 RA OVC050 14/05 A2965 RMK AO2
In the example above, the Depart =3D=20 lines[1].split()[0] always works because all files start that way. The = code will=20 print out KPVD 2001/10/23 KLGA. This is perfect if all reports contained = the=20 same number of lines. If, however, another report has all the = information=20 contained in two lines instead ot three, the Destin1 =3D = lines[5].split()[0]=20 will give me an out of range error, and the Destin =3D = lines[4].split()[0] will=20 give me 2001/10/23 instead of KLGA.
 
So this is where I get lost. It would seem that a simple" if = condition"=20 checking for either a null string or something other than a null would = do the=20 trick. i would then replace the actual numbers in the bracket s with = variables=20 that would point to the correct line. The problem is that I cannot use = the=20 line[].split()[] statement to do the checking without first getting the = "out of=20 range error" in an if condition. What other "simple" routine can I use = to ensure=20 avoidance of that error? thank you. = tony

------=_NextPart_000_0007_01C15EB4.4202F9A0-- ---------------------------------------------------- Sign Up for NetZero Platinum Today Only $9.95 per month! http://my.netzero.net/s/signup?r=platinum&refcd=PT97 From ak@silmarill.org Sat Oct 27 15:22:43 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Sat, 27 Oct 2001 10:22:43 -0400 Subject: [Tutor] Python performance on Windows system In-Reply-To: <002701c15ea3$cdb33ac0$98a0d6d1@joeltklrijxxms> References: <002701c15ea3$cdb33ac0$98a0d6d1@joeltklrijxxms> Message-ID: <20011027102243.A15241@sill.silmarill.org> On Sat, Oct 27, 2001 at 12:56:54AM -0400, Joel Ricker wrote: > Hi all, > > I've been away from Python for a little while and so to stretch my programming legs a little bit, I've been working on a script to generate prime numbers. I've used a sieve algorithm and originally a list of numbers in an array and have reworked it to use a text file in the same way. I've noticed when working with big numbers, say finding all prime numbers between 1 and 5 million, my system becomes a little less responsive. It was real bad when I used a large array since sometimes the memory used by python would run into the 100 meg range but since I've switched to using a file it has improved alot but its still there. > > Basically what happens is while the script is running, other windows are a little Yeah, probably.. I didn't read the code but you can save up a bunch of numbers and then write them out.. caching, in other words. - Andrei [snip] > I hear task manager isn't very accurate. > Is it all the disk writes that is slowing things down? Anything I can do to my code to help things along? Or anything I can do to the python interpreter itself? Below is the main part of the code that is doing most of the work in the script. primein.txt is a text file containing a list of numbers between 0 and the max number to search to. > > Thanks > Joel > > f = open('primein.txt','r+') > x = 2 > endsqrt = math.floor(math.sqrt(end)) > while x <= endsqrt: > print x > for y in xrange(2, end/x+1): > f.seek(x * y * 12) > f.write('%10d\n' % 0) > f.flush() > f.seek(x * 12 + 12) > while 1: > x = f.readline() > if int(x) > 0: > x = int(x) > break -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From r.b.rigilink@chello.nl Sat Oct 27 15:55:09 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Sat, 27 Oct 2001 16:55:09 +0200 Subject: [Tutor] More help needed in sorting files and strings References: <000a01c15ed5$ca3991a0$d280f4d1@w9y5d5> Message-ID: <3BDACACD.6F4F5E0C@chello.nl> > tonycervone wrote: > > Hi all. > > I have been using this code to read weather reports and to print only > the first two stations symbols in the file: > inp =open("Metar\Infometar.txt") > lines = inp.readlines() > Depart = lines[1].split()[0] > Destin = lines[4].split()[0] > Destin1 = lines[5].split()[0] > Print Depart+" "+Destin+" "+Destin1 > > This code works fine until it finds an empty line and then I get an > out of range error. Here's why: > > 2001/10/23 21:18 > KPVD 232118Z AUTO 22014KT 3/4SM +TSRA BKN021 OVC033 20/14 A2937 > RMK AO2 > > 2001/10/23 21:18 > KLGA 232118Z AUTO 23008KT 6SM -SHRA BKN012 18/17 A2962 RMK > AO2 > > 2001/10/23 21:18 > KBDL 232118Z AUTO 01012KT 6SM RA OVC050 14/05 A2965 RMK AO2 Hi Tony, As far as I can tell, the layout of your data file follows the following rules. - The file contains one or more records - The first record starts at the first line of the file - Each record contains the following o A line with a date and a time o One or more lines with station information o A blank line Because you don't know beforehand if records contain one or two lines of station data, you don't know at what line to look for data for the second (or third, or n'th) weather station Since you don't know at what line a given record is, you have to search for the record using the previous rules. If you want to get the 2nd station, you could do one of two things: 1. look for the 2nd line with a date and a time, the data you're interested in is on the next line 2. look for the 2nd empty line, the data you're interested in is somewhere along the lines before that. In the code below I'm going to give a somewhat more general solution First I'm going to assemble all data in a list of records. Each record in this list will itself be a list of all data that the file contains for a given record. I'm going to use the fact that records are separated by blank lines to distinguish between subsequent records. -- start script ------------------------------ inp = open('tmp.dat') line_list = inp.readlines() record_list = [] record = [] for line in line_list: line = line.strip() if line == '': # blank line encountered, add the current record to the # record_list and start assembling a new record record_list.append(record) record = [] else: # add all data items in this line to the current record record.extend(line.split()) #in case the file didn't end with a blank line if len(record) > 0: record_list.append(record) for record in record_list: print record print record_list[0][2] -- end script --------------------------------- Using this file 'tmp.dat': -- tmp.dat ------------------------------------ 2001/10/23 21:18 KPVD 232118Z AUTO 22014KT 3/4SM +TSRA BKN021 OVC033 20/14 A2937 RMK AO2 2001/10/23 21:18 KLGA 232118Z AUTO 23008KT 6SM -SHRA BKN012 18/17 A2962 RMK AO2 2001/10/23 21:18 KLGA 232118Z AUTO 23008KT 6SM -SHRA BKN012 18/17 A2962 RMK AO2 -- end tmp.dat -------------------------------- I get the following result: ['2001/10/23', '21:18', 'KPVD', '232118Z', 'AUTO'] ['2001/10/23', '21:18', 'KLGA', '232118Z', 'AUTO'] ['2001/10/23', '21:18', 'KLGA', '232118Z', 'AUTO'] KPVD Note that record_list[i][j] will give you the j'th data item of the i'th record, counting from zero. Hope this helps, Roeland -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From alan.gauld@bt.com Sat Oct 27 17:01:17 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sat, 27 Oct 2001 17:01:17 +0100 Subject: [Tutor] Why different behaviours? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C036@mbtlipnt02.btlabs.bt.co.uk> > import string, sys > f=open('d:/Dokument/Programprojekt/pythonworks/projects/H2/Lex > icon.txt', 'r') > for line in f.readline(): readline returns a string, line will therefore take the value of each char in the string. > Also, what would be the way to read line after line until end > of file. How to detect end of file when reading a sequential > file this way? If its a short-medium file use: for line in f.readlines(): # note plural! or for long files: for line in f.xreadlines(): # x stops it all being read at once Alternatively: while 1: try: line = f.readline() print line except: break There are other variations. For more words explaining whats going on try my tutor at: http://www.freenetpages.co.uk/hp/alan.gauld/ look under the files topic... Alan G From alan.gauld@bt.com Sat Oct 27 17:07:34 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sat, 27 Oct 2001 17:07:34 +0100 Subject: [Tutor] Pretty and invisible Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C037@mbtlipnt02.btlabs.bt.co.uk> > Second, I would like to either not echo or obscure the > password raw_input(). Look at the passwd module. Batteries are included... :-) Alan g From sarnold@earthling.net Sat Oct 27 17:12:09 2001 From: sarnold@earthling.net (Stephen L Arnold) Date: Sat, 27 Oct 2001 09:12:09 -0700 Subject: [Tutor] new Linux Installation In-Reply-To: <3BD9E5C4.2D479D3F@venix.com> Message-ID: <20011027161209.4716A1FB01@shiva.arnolds.bogus> On 26 Oct 01, at 18:37, Lloyd Kvam wrote: [snip] > I have a choice of Gnome and KDE. Does it matter? Presumably I > will be using Tkinter for Python based GUI programming. Does > Tkinter care? I don't think it really matters, but you will probably want to upgrade to the current python. Also, some good web frameworks based on python (as an alternative to CGI) are Zope and Webware: http://www.zope.org http://webware.sourceforge.net/ They're both way better than writing your own CGI scripts, but there's a bit of of a learning curve (well worth it IMHO). As far as X desktops go, everyone has their preference. I prefer Gnome to KDE, but I like Enlightenment best of all. I'm using E 16.5 right now (it's an easy rpm install on a RedHat box) and I think it's the coolest thing out there, but when E 17 comes out it will blow the doors off of everything else. I also use BlackBox on an older laptop (it's very lightweight but functional). But nothing looks as cool as the E image rendering... And make sure you try one of the recent Eterm releases with the backgrounds. There are some E screenshots (and one Ximian Gnome) on one of my cheesy web pages: http://arnolds.dhs.org/screenshots.html HTH, Steve ************************************************************* Steve Arnold http://arnolds.dhs.org Java is for staying up late while you program in Python... From alan.gauld@bt.com Sat Oct 27 18:02:43 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sat, 27 Oct 2001 18:02:43 +0100 Subject: [Tutor] More help needed in sorting files and strings Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C038@mbtlipnt02.btlabs.bt.co.uk> ------_=_NextPart_001_01C15F09.3161EC50 Content-type: text/plain; charset="ISO-8859-1" > inp =open("Metar\Infometar.txt") > lines = inp.readlines() so far so good. > Depart = lines[1].split()[0] This is OK because you know its always in line 1 Now lets become a bit more flexible. What we want is the second record which will be after the first blank line. current = 2 while lines[current]: # empty line counts as false current += 1 current will now point at the next blank line. We want to extract the data from the first then second line of the record so add 1 and 2 to current in the indices: Destin = lines[current+1].split()[0] Destin1 = lines[ current+2 ].split()[0] Print Depart+" "+Destin+" "+Destin1 You can repeat that technique until all the records you need are found. Once you get more experienced you will discover better ways of working using functions which you define and later still, objects which can read themseles from files etc... But for now try variations on my(untested!) code above. HTH, Alan g ------_=_NextPart_001_01C15F09.3161EC50 Content-type: text/html; charset="ISO-8859-1"
    > inp =open("Metar\Infometar.txt")
    > lines = inp.readlines() 
 
so far so good.
 
    > Depart = lines[1].split()[0]
 
This is OK because you know its always in line 1
 
Now lets become a bit more flexible. What we want
is the second record which will be after the first
blank line.
 
    current = 2
    while lines[current]:   # empty line counts as false
        current += 1
 
current will now point at the next blank line.
We want to extract the data from the first then
second line of the record so add 1 and 2 to
current in the indices:
 
    Destin = lines[current+1].split()[0]
    Destin1 = lines[ current+2 ].split()[0]   
    Print Depart+" "+Destin+" "+Destin1
 
You can repeat that technique until all the records
you need are found.
 
Once you get more experienced you will discover
better ways of working using functions which you
define and later still, objects which can read
themseles from files etc... But for now try
variations on my(untested!) code above.
 
HTH,
 
Alan g
 
------_=_NextPart_001_01C15F09.3161EC50-- From kalle@gnupung.net Sat Oct 27 18:17:30 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Sat, 27 Oct 2001 19:17:30 +0200 Subject: [Tutor] Pretty and invisible In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C037@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C037@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20011027191730.A57@sandra.lysator.liu.se> [alan.gauld@bt.com] > > Second, I would like to either not echo or obscure the > > password raw_input(). > > Look at the passwd module. > Batteries are included... :-) That should be the getpass module, IIRC. Peace, Kalle -- [ Thought control, brought to you by the WIPO! ] [ http://anti-dmca.org/ http://eurorights.org/ ] From myuen@ucalgary.ca Sun Oct 28 01:49:24 2001 From: myuen@ucalgary.ca (Mike Yuen) Date: Sat, 27 Oct 2001 19:49:24 -0600 (MDT) Subject: [Tutor] Filter Message-ID: I'm having some trouble understanding how to use the filter function. My understanding is that say I have a series of numbers like: 4732789123895231 And I want to remove all occurences of 1,2,3. How do I do this? From dsh8290@rit.edu Sun Oct 28 02:44:07 2001 From: dsh8290@rit.edu (dman) Date: Sat, 27 Oct 2001 22:44:07 -0400 Subject: [Tutor] Filter In-Reply-To: ; from myuen@ucalgary.ca on Sat, Oct 27, 2001 at 07:49:24PM -0600 References: Message-ID: <20011027224407.A1159@buddy.cs.rit.edu> On Sat, Oct 27, 2001 at 07:49:24PM -0600, Mike Yuen wrote: | I'm having some trouble understanding how to use the filter function. My | understanding is that say I have a series of numbers like: | | 4732789123895231 What do you mean by a "series"? Is it a list, tuple, string, something else? | And I want to remove all occurences of 1,2,3. | | How do I do this? >>> def should_keep( num ) : ... return num not in ( 1 , 2 , 3 ) ... >>> my_series = [ 4,7,3,2,7,8,9,1,2,3,8,9,5,2,3,1 ] >>> print filter( should_remove , my_series ) [4, 7, 7, 8, 9, 8, 9, 5] >>> You define a function that returns a boolean indicating whether or not you want to keep the specified element. The filter function runs through the sequence ("my_series") and calls the function ("should_remove") passing each element in turn as the argument. For those elements for which the function returns true, it puts it into a new list. The others are ignored. filter then returns that new list it built. Another technique is to use list comprehensions. This requires python 2.0 or newer. >>> my_series = [ 4,7,3,2,7,8,9,1,2,3,8,9,5,2,3,1 ] >>> print [x for x in my_series if x not in (1,2,3) ] [4, 7, 7, 8, 9, 8, 9, 5] >>> It is more compact, though it is a little harder to become familiar with, I think. HTH, -D From r.b.rigilink@chello.nl Sun Oct 28 11:32:48 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Sun, 28 Oct 2001 12:32:48 +0100 Subject: [Tutor] Python performance on Windows system References: <002701c15ea3$cdb33ac0$98a0d6d1@joeltklrijxxms> Message-ID: <3BDBECE0.6900EBDD@chello.nl> Hi Joel, The problem is certainly the disk read/writes. As you found out, trying to manipulate a large list of integers consumes a lot of memory. A python integer (an integer object) takes about 20 bytes (IIRC), so 100M of memory for a list of 5 milion integers sounds about right. However the integer value itself is only 4 bytes. So, if you use the array module to store the integers in an array, you already slash your memory consumption to 20M. However, there is a nice trick that can reduce the memory consumption a lot more. It's a variation on the trick you could have used with your file too. Note that your file lists all the integers from 1 to end, using 12 bytes per number (10 chars+'\r'+'\n'). However, to see if number n is a prime you compute an offset (n*12) and read the line to see if the number is n (then it's a prime) or 0 then it's not. But, since you already know the number you're interested in, why store it. You could just as easily have made a file with either a 1 or a 0 on each line (costing only three bytes) use n to compute the offset (n*3) and get either a 0 (not prime) or 1 (prime). Or, just store it as one long string of 0s and 1s. The cost would have been one byte per number and the offset for number n would have been n. But, 0 or 1 that's not a byte, that's a bit. It should be possible to store the result for eight numbers in 1 byte. Reducing the memory/disk cost from 20/12 bytes per number to 1 byte per 8 numbers. That's a factor of a hundred. Now, that's a significant factor. With your current method you'll start getting into trouble again if you try to do 80M numbers, since you'll then get in the 1GB limit on your file size. However, if you could reduce the cost to 1 byte per 8 number, Those same 80M numbers would fit comfortably in about 10M of memory without any need to use disk access at all. Without further ado, here's a class (bitset) that packs the information you're interested in. It uses the fact that an integer contains 32 bits. So I can store n bits of information in an array of n/32 integers. I also include a version of your sieve algorithm that uses the bitset to store its result. import math, array, time class bitset: '''A class to hold a bitset of arbitrary length The bitset is stored in chunks of 32 bits.''' def __init__(self, size): self.size = size self.data = array.array('l', [0]*int(math.ceil(size/32.0))) def setbit(self, index): '''set bit at index to true''' arrindex, bitindex = divmod(index, 32) self.data[arrindex] |= (1< Joel Ricker wrote: > > Hi all, > > I've been away from Python for a little while and so to stretch my > programming legs a little bit, I've been working on a script to > generate prime numbers. I've used a sieve algorithm and originally a > list of numbers in an array and have reworked it to use a text file in > the same way. I've noticed when working with big numbers, say finding > all prime numbers between 1 and 5 million, my system becomes a little > less responsive. It was real bad when I used a large array since > sometimes the memory used by python would run into the 100 meg range > but since I've switched to using a file it has improved alot but its > still there. > > Basically what happens is while the script is running, other windows > are a little slow to appear and starting new programs or closing > windows takes several seconds to hapen. I'm running Windows 2000, > with a 750 mhz processor and 128megs of memory. What is odd though is > that using Task Manager, I see that Python isn't using that much CPU > -- only 1 or 2 percent at the most and very little memory -- about > 520k. > > Is it all the disk writes that is slowing things down? Anything I can > do to my code to help things along? Or anything I can do to the > python interpreter itself? Below is the main part of the code that is > doing most of the work in the script. primein.txt is a text file > containing a list of numbers between 0 and the max number to search > to. > > Thanks > Joel > > f = open('primein.txt','r+') > x = 2 > endsqrt = math.floor(math.sqrt(end)) > while x <= endsqrt: > print x > for y in xrange(2, end/x+1): > f.seek(x * y * 12) > f.write('%10d\n' % 0) > f.flush() > f.seek(x * 12 + 12) > while 1: > x = f.readline() > if int(x) > 0: > x = int(x) > break -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From nhytro-python@web.de Sun Oct 28 10:51:18 2001 From: nhytro-python@web.de (nhytro-python@web.de) Date: Sun, 28 Oct 2001 11:51:18 +0100 Subject: [Tutor] Message-ID: <200110281051.f9SApIu05193@mailgate5.cinetic.de> I have the "backslash" problem with an application I=B4m developing. I know = about escaping forward slashes or using raw strings, but things are not wo= rking as I expect. A code snippet: #################code -start def go=5Frender(): ........textfile =3D inputfile.get() # inputfile is a tkintet entry widget ........textfile =3D string.replace(textfile, '\\', '\\\\') ........editor =3D editorpath.get()# editorpath is a tkinter entry widget ........editor =3D string.replace(editor, '\\', '\\\\') ........os.system(r"%s %s" % (editor, textfile)) ........ ############## end code snippet this function is a callback function for a tkinter button. Nothing happens= when I press the button. Writing out the full paths like: ........os.system("c:\notepad" "mytext.txt") works, but the values are taken interactively from entry wdgets from my ap= plication. Does someone see what I do=B4nt see=3F could someone point out my m= istake=3F Great thanks in advance Sharriff =5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F Lotto online tippen! Egal zu welcher Zeit, egal von welchem Ort. Mit dem WEB.DE Lottoservice. http://tippen2.web.de/=3Fx=3D13 From nhytro-python@web.de Sun Oct 28 12:26:36 2001 From: nhytro-python@web.de (nhytro-python@web.de) Date: Sun, 28 Oct 2001 13:26:36 +0100 Subject: [Tutor] Commandline and backslash problem Message-ID: <200110281226.f9SCQau02803@mailgate5.cinetic.de> I have the "backslash" problem with an application I=B4m developing. I know = about escaping forward slashes or using raw strings, but things are not wo= rking as I expect. A code snippet: #################code -start def go=5Frender(): ........textfile =3D inputfile.get() # inputfile is a tkintet entry widget ........textfile =3D string.replace(textfile, '\\', '\\\\') ........editor =3D editorpath.get()# editorpath is a tkinter entry widget ........editor =3D string.replace(editor, '\\', '\\\\') ........os.system(r"%s %s" % (editor, textfile)) ........ ############## end code snippet this function is a callback function for a tkinter button. Nothing happens= when I press the button. Writing out the full paths like: ........os.system("c:\notepad" "mytext.txt") works, but the values are taken interactively from entry wdgets from my ap= plication. Does someone see what I do=B4nt see=3F could someone point out my m= istake=3F Great thanks in advance =5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F Lotto online tippen! Egal zu welcher Zeit, egal von welchem Ort. Mit dem WEB.DE Lottoservice. http://tippen2.web.de/=3Fx=3D13 From r.b.rigilink@chello.nl Sun Oct 28 17:22:45 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Sun, 28 Oct 2001 18:22:45 +0100 Subject: [Tutor] Commandline and backslash problem References: <200110281226.f9SCQau02803@mailgate5.cinetic.de> Message-ID: <3BDC3EE5.70C39C50@chello.nl> Hi, Are you sure this is a backslash problem I made this little testprogram, and as far as I can tell Entry.get() is smart about escaping the backslashes. from Tkinter import * def ev(*args): t =3D e.get() print t, repr(t) e =3D Entry() e.pack() b =3D Button(text=3D'do', command=3Dev) b.pack() mainloop() Some example output a\b 'a\\b' a\b\\c\t\n 'a\\b\\\\c\\t\\n' nhytro-python@web.de wrote: > = > I have the "backslash" problem with an application I=B4m developing. I = know about escaping forward slashes or using raw strings, but things are = not working as I expect. A code snippet: > = > #################code -start > = What do you get if you replace go_render with: def go_render(): textfile =3D inputfile.get() print textfile editor =3D editorpath.get() print editor os.system("%s %s" % (editor, textfile)) As far as I can tell there's no need to do the string replacement Hope this helps, Roeland -- = r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From nhytro-python@web.de Sun Oct 28 20:52:35 2001 From: nhytro-python@web.de (nhytro-python@web.de) Date: Sun, 28 Oct 2001 21:52:35 +0100 Subject: [Tutor] Commandline and backslash problem Message-ID: <200110282052.f9SKqZu05162@mailgate5.cinetic.de> Quite right Roeland! I noticed this also 30mins ago, my application works = "halfway" now. The wierdest, saddest thing is that switches don=B4t work wit= h os.system(): ### example def howzat(): ....prog =3D "C:\\blah.exe" ....switch =3D "-q" ....file =3D "aha.txt" os.system("%s %s %s" %(prog, switch, file)) #### end example the commandline application mentions "error, file not found-> -q" , appare= ntly it thinks that the switch is a file, this is then skipped and it exec= utes but without the switch. Are switches built this way passed separately to the commandline=3F I took a= look at execl and spawnv, they did=B4nt work in my function, they just did = not execute the commandline application :-(=20 Roeland Rengelink schrieb am 28.10.01: Hi, Are you sure this is a backslash problem I made this little testprogram, and as far as I can tell Entry.get() is smart about escaping the backslashes. from Tkinter import * def ev(*args): t =3D e.get() print t, repr(t) e =3D Entry() e.pack() b =3D Button(text=3D'do', command=3Dev) b.pack() mainloop() Some example output a\b 'a\\b' a\b\\c\t\n 'a\\b\\\\c\\t\\n' nhytro-python@web.de wrote: >=20 > I have the "backslash" problem with an application I=B4m developing. I kno= w about escaping forward slashes or using raw strings, but things are not = working as I expect. A code snippet: >=20 > #################code -start >=20 What do you get if you replace go=5Frender with: def go=5Frender(): textfile =3D inputfile.get() print textfile editor =3D editorpath.get() print editor os.system("%s %s" % (editor, textfile)) As far as I can tell there's no need to do the string replacement Hope this helps, Roeland --=20 r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" =20 =5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F Lotto online tippen! Egal zu welcher Zeit, egal von welchem Ort. Mit dem WEB.DE Lottoservice. http://tippen2.web.de/=3Fx=3D13 From scarblac@pino.selwerd.nl Sun Oct 28 21:18:31 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Sun, 28 Oct 2001 22:18:31 +0100 Subject: [Tutor] Commandline and backslash problem In-Reply-To: <200110282052.f9SKqZu05162@mailgate5.cinetic.de>; from nhytro-python@web.de on Sun, Oct 28, 2001 at 09:52:35PM +0100 References: <200110282052.f9SKqZu05162@mailgate5.cinetic.de> Message-ID: <20011028221831.A25331@pino.selwerd.nl> On 0, nhytro-python@web.de wrote: > Quite right Roeland! I noticed this also 30mins ago, my application works > "halfway" now. The wierdest, saddest thing is that switches don´t work with > os.system(): > > ### example > def howzat(): > ....prog = "C:\\blah.exe" > ....switch = "-q" > ....file = "aha.txt" > os.system("%s %s %s" %(prog, switch, file)) > #### end example > > the commandline application mentions "error, file not found-> -q" , > apparently it thinks that the switch is a file, this is then skipped and it > executes but without the switch. This is in fact proof that os.system() gave the switch to the command blah.exe; that blah.exe doesn't know that it is a switch, well that's not something os.system can do anything about... > Are switches built this way passed separately to the commandline? I took a > look at execl and spawnv, they did´nt work in my function, they just did not > execute the commandline application :-( No, it's just one command line. blah.exe doesn't have a switch '-q'. -- Remco Gerlich From alan.gauld@bt.com Sun Oct 28 21:32:56 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 28 Oct 2001 21:32:56 -0000 Subject: [Tutor] Commandline and backslash problem Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C039@mbtlipnt02.btlabs.bt.co.uk> > def go_render(): > ........textfile = inputfile.get() # inputfile is a tkintet > ........textfile = string.replace(textfile, '\\', '\\\\') > ........editor = editorpath.get()# editorpath is a tkinter > ........editor = string.replace(editor, '\\', '\\\\') > ........os.system(r"%s %s" % (editor, textfile)) > ........ > ############## end code snippet > Nothing happens when I press the button. Writing out the full > ........os.system("c:\notepad" "mytext.txt") > works, Suggests you aren't getting the right values. Have you tried putting print statements in and looking at the output in the console? Just print the values immediately after the get() and again before calling system() That will definitively determine whether you are getting values out of the widget and whether the replace works. Failing that can you show us the bit of Tkinter code where you build the entry widgets and the button that calls the handler above. Alan g From alan.gauld@bt.com Sun Oct 28 21:34:48 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 28 Oct 2001 21:34:48 -0000 Subject: [Tutor] Pretty and invisible Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C03A@mbtlipnt02.btlabs.bt.co.uk> > > Look at the passwd module. > > Batteries are included... :-) > > That should be the getpass module, IIRC. Quite possibly, I just meant that there was a module for handling passwords... Alan g From nhytro-python@web.de Sun Oct 28 21:44:53 2001 From: nhytro-python@web.de (nhytro-python@web.de) Date: Sun, 28 Oct 2001 22:44:53 +0100 Subject: [Tutor] commandline, os.system, backslash revisted Message-ID: <200110282144.f9SLiru26454@mailgate5.cinetic.de> Seems like I spoke to soon. I tried out several things and noticed that this worked: #### code snippet def go_app(): ........textfile = inputfile.get() # inputfile is a tkintet entry widget ........textfile = string.replace(textfile, '/', '\\') ........editor = editorpath.get()# editorpath is a tkinter entry widget ........editor = string.replace(editor, '/', '\\') ........editor = editor + " -test" # switch test ........os.system(r"%s %s" % (editor, textfile)) ........ ############## end code I tried out a file that had "dangerous" characters: c:\the\boy.txt the commandline application was correctly called but the file above caused a "file not found" error. I did a print to screen and saw that the path was trashed: " theoy.txt " Is there no sure way to run commandline executables with switches with os.sytem? also switches built into a command (example "c:\foo.exe -test") always fail, with a file not found error. This is very saddening, any clues? help? Thanks in advance Sharriff ________________________________________________________________ Lotto online tippen! Egal zu welcher Zeit, egal von welchem Ort. Mit dem WEB.DE Lottoservice. http://tippen2.web.de/?x=13 From nhytro-python@web.de Sun Oct 28 21:56:51 2001 From: nhytro-python@web.de (nhytro-python@web.de) Date: Sun, 28 Oct 2001 22:56:51 +0100 Subject: [Tutor] Commandline and backslash problem Message-ID: <200110282156.f9SLupu19016@mailgate5.cinetic.de> Hello Remco! Thanks for your help but this assumption is wrong, the application is a frontend to a commandline application that I have used with these switches often, the switches exist and they were not misspelled. Remoco wrote: >This is in fact proof that os.system() gave the switch to the command >blah.exe; that blah.exe doesn't know that it is a switch, well that's not >something os.system can do anything about... -- Remco Gerlich ________________________________________________________________ Lotto online tippen! Egal zu welcher Zeit, egal von welchem Ort. Mit dem WEB.DE Lottoservice. http://tippen2.web.de/?x=13 From dsh8290@rit.edu Sun Oct 28 22:14:46 2001 From: dsh8290@rit.edu (dman) Date: Sun, 28 Oct 2001 17:14:46 -0500 Subject: [Tutor] commandline, os.system, backslash revisted In-Reply-To: <200110282144.f9SLiru26454@mailgate5.cinetic.de>; from nhytro-python@web.de on Sun, Oct 28, 2001 at 10:44:53PM +0100 References: <200110282144.f9SLiru26454@mailgate5.cinetic.de> Message-ID: <20011028171446.A4254@buddy.cs.rit.edu> On Sun, Oct 28, 2001 at 10:44:53PM +0100, nhytro-python@web.de wrote: | Seems like I spoke to soon. | | I tried out several things and noticed that this worked: | | #### code snippet | | def go_app(): | ........textfile = inputfile.get() # inputfile is a tkintet entry widget | ........textfile = string.replace(textfile, '/', '\\') | ........editor = editorpath.get()# editorpath is a tkinter entry widget | ........editor = string.replace(editor, '/', '\\') | ........editor = editor + " -test" # switch test | ........os.system(r"%s %s" % (editor, textfile)) | ........ | ############## end code | | I tried out a file that had "dangerous" characters: | c:\the\boy.txt | | the commandline application was correctly called but the file above | caused a "file not found" error. I did a print to screen and saw | that the path was trashed: " theoy.txt " | | Is there no sure way to run commandline executables with switches | with os.sytem? also switches built into a command (example | "c:\foo.exe -test") always fail, with a file not found error. | | This is very saddening, any clues? help? Yeah, MS' choice to use backslash characters as "normal" characters causes more headaches. I had many problems with them when I was working with windows and cygwin. The only solution I know of is to repeatedly escape the backslashes until you are certain that the string won't be evaluated any more. So even though Tkinter gives you one level of escaping already, add another and see if that works. If not, try adding a third. -D From danny.kohn@systematik.se Sun Oct 28 23:04:17 2001 From: danny.kohn@systematik.se (Danny Kohn) Date: Mon, 29 Oct 2001 00:04:17 +0100 Subject: [Tutor] String.find won't - why? Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0002_01C1600D.405F3FF0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi again. Thanks for all the comments on the readline(s) issue. I have understood = this fully. But please bear with me. Unfortunally the next step in this little = program is as problematic for me. Am trying to remove all 0D 0A (Hex). Thought this was done through the = following while loop. The file is attached. The first round things works nicely. The 0D 0A (Hex) is found and = removed. Pos is correctly 142. The second round things behave more strangely. Pos will get a wrong = value (178) but there just is no 0D 0A (Hex) there and so the i:pos = string will get to short. Running w2k. Why on earth is this behaving wrongly? t =3D open('d:/Experiment.txt', 'r') text =3D t.read() # Read text t.close() print text print i=3D0 a =3D '' while i < len(text): pos =3D string.find(text[i:], '\n') print pos if pos > 0: a =3D a + text[i:pos] print a print i =3D i + pos + 1 /Danny ------=_NextPart_000_0002_01C1600D.405F3FF0 Content-Type: text/plain; name="Experiment.txt" Content-Transfer-Encoding: quoted-printable Content-Disposition: attachment; filename="Experiment.txt" Comments that contradict the code are worse than no comments. Always = make a priority of keeping the comments up-to-date when the code = changes! If a comment is a phrase or sentence, its first word should be = capitalized, unless it is an identifier that begins with a lower case = letter (never alter the case of identifiers!). If a comment is short, the period at the end is best omitted. Block = comments generally consist of one or more paragraphs built out of = complete sentences, and each sentence should end in a period. You can use two spaces after a sentence-ending period. As always when writing English, Strunk and White apply. Python coders from non-English speaking countries: please write your = comments in English, unless you are 120% sure that the code will never = be read by people who don't speak your language. Block comments generally apply to some (or all) code that follows them, = and are indented to the same level as that code. Each line of a block = comment starts with a # and a single space (unless it is indented text = inside the comment). Paragraphs inside a block comment are separated by = a line containing a single #. Block comments are best surrounded by a = blank line above and below them (or two lines above and a single line = below for a block comment at the start of a a new section of function = definitions). ------=_NextPart_000_0002_01C1600D.405F3FF0-- From scarblac@pino.selwerd.nl Sun Oct 28 23:13:31 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Mon, 29 Oct 2001 00:13:31 +0100 Subject: [Tutor] String.find won't - why? In-Reply-To: ; from danny.kohn@systematik.se on Mon, Oct 29, 2001 at 12:04:17AM +0100 References: Message-ID: <20011029001330.A25494@pino.selwerd.nl> On 0, Danny Kohn wrote: > Hi again. > Thanks for all the comments on the readline(s) issue. I have understood this fully. > But please bear with me. Unfortunally the next step in this little program is as problematic for me. > Am trying to remove all 0D 0A (Hex). Thought this was done through the following while loop. > The file is attached. 0D 0A? That's CRLF right, a newline on Windows/DOS. Ok. > The first round things works nicely. The 0D 0A (Hex) is found and removed. Pos is correctly 142. > The second round things behave more strangely. Pos will get a wrong value (178) but there just is no 0D 0A (Hex) there and so the i:pos string will get to short. > Running w2k. Why on earth is this behaving wrongly? > > t = open('d:/Experiment.txt', 'r') > > text = t.read() # Read text > t.close() > > print text > print > > i=0 > a = '' > while i < len(text): > pos = string.find(text[i:], '\n') Here, pos gets a position relative to text[i:]. > print pos > if pos > 0: > a = a + text[i:pos] Here you use pos as an index in the whole string. So you meant a = a + text[i:i+pos]. The reason this works the first time is that it's the same thing with i=0. > print a > print > i = i + pos + 1 > > /Danny Btw, the whole loop can be written a = string.replace(text, '\n', '') Hope this helps :) -- Remco Gerlich From danny.kohn@systematik.se Sun Oct 28 23:44:01 2001 From: danny.kohn@systematik.se (Danny Kohn) Date: Mon, 29 Oct 2001 00:44:01 +0100 Subject: SV: [Tutor] String.find won't - why? In-Reply-To: <20011029001330.A25494@pino.selwerd.nl> Message-ID: | -----Ursprungligt meddelande----- | Fran: tutor-admin@python.org [mailto:tutor-admin@python.org]For Remco | Gerlich | Skickat: den 29 oktober 2001 00:14 | So you meant a =3D a + text[i:i+pos]. |=20 | The reason this works the first time is that it's the same thing with = i=3D0. Yes, you are so correct. How stupid of me. Thanks. /Danny From wilson@visi.com Mon Oct 29 04:19:21 2001 From: wilson@visi.com (Timothy Wilson) Date: Sun, 28 Oct 2001 22:19:21 -0600 (CST) Subject: [Tutor] proper return style Message-ID: Hi everyone, What's the rule about using a explicit return command in functions? For example: def printSquare(number): print number**2 return works the same as: def printSquare(number): print number**2 What's preferred? -Tim -- Tim Wilson | Visit Sibley online: | Check out: Henry Sibley HS | http://www.isd197.org | http://www.zope.com W. St. Paul, MN | | http://slashdot.org wilson@visi.com | | http://linux.com From tim.one@home.com Mon Oct 29 04:43:55 2001 From: tim.one@home.com (Tim Peters) Date: Sun, 28 Oct 2001 23:43:55 -0500 Subject: [Tutor] proper return style In-Reply-To: Message-ID: [Timothy Wilson] > What's the rule about using a explicit return command in functions? For > example: > > def printSquare(number): > print number**2 > return > > works the same as: > > def printSquare(number): > print number**2 > > What's preferred? My rule is to leave off the "return" unless the function is intended to return an explicit result. So def printSquare(number): print number**2 def square(number): return number**2 Note that if a function intends to return None as an explict value, then an explict return None is much better than the equivalent return or falling off the end. "Functions" used solely for side-effects (such as your printSquare) are clearest if they don't use "return" at all. From chimaadams@yahoo.com Mon Oct 29 10:28:15 2001 From: chimaadams@yahoo.com (chima adams) Date: Mon, 29 Oct 2001 11:28:15 +0100 Subject: [Tutor] (no subject) Message-ID: FROM THE DESK:Dr.CHIMA ADAMS, ACCOUNT DEPARTMENT (NNPC) FALOMO OFFICE COMPLEX, IKOYI – LAGOS, NIGERIA TEL:234-8033084103 FAX: 234-1-7599186 ATTN: GENERAL MANAGER Dear Sir, I am Dr.Chima Adams chairman- audit committee, with the Nigerian National Petroleum Corporation (NNPC), I headed the audit committee whose assignment was to audit, review and recommend payment for all contracts awarded in the NNPC by the corrupt past military administration. In the course of our review, we discovered that the sum of USD 30 million (THIRTY MILLION DOLLARS) was floating unclaimed in the corporation account without beneficiary. This money emanated from an over-invoicing in the contract awarded to a foreign firm for the supply, fixing, erecting and computerized optimization of oil pipeline to one of our oil refineries during the past Military administration. Base on our status as senior government officials in top sensitive position of trust, we cannot stand to claim this money ourselves, hence, I decided to contact you. All modalities for this transfer have been fully worked out. We have already secured a preliminary order to effect this payment, we now require from you your BANKING PARTICULARS, FAX AND TELEPHONE NUMBER for smooth transfer of this money into your bank account. We intend to share the money in the following manner: 30% for you, 65% for us and 5% for any miscellaneous expenses. This business is 100% risk-free. We look forward to a fruitful business relationship with you. Best Regards Dr. Chima Adams Account Department (NNPC) _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From chimaadams@yahoo.com Mon Oct 29 10:42:53 2001 From: chimaadams@yahoo.com (chima adams) Date: Mon, 29 Oct 2001 11:42:53 +0100 Subject: [Tutor] (no subject) Message-ID: FROM THE DESK:Dr.CHIMA ADAMS, ACCOUNT DEPARTMENT (NNPC) FALOMO OFFICE COMPLEX, IKOYI – LAGOS, NIGERIA TEL:234-8033084103 FAX: 234-1-7599186 ATTN: GENERAL MANAGER Dear Sir, I am Dr.Chima Adams chairman- audit committee, with the Nigerian National Petroleum Corporation (NNPC), I headed the audit committee whose assignment was to audit, review and recommend payment for all contracts awarded in the NNPC by the corrupt past military administration. In the course of our review, we discovered that the sum of USD 30 million (THIRTY MILLION DOLLARS) was floating unclaimed in the corporation account without beneficiary. This money emanated from an over-invoicing in the contract awarded to a foreign firm for the supply, fixing, erecting and computerized optimization of oil pipeline to one of our oil refineries during the past Military administration. Base on our status as senior government officials in top sensitive position of trust, we cannot stand to claim this money ourselves, hence, I decided to contact you. All modalities for this transfer have been fully worked out. We have already secured a preliminary order to effect this payment, we now require from you your BANKING PARTICULARS, FAX AND TELEPHONE NUMBER for smooth transfer of this money into your bank account. We intend to share the money in the following manner: 30% for you, 65% for us and 5% for any miscellaneous expenses. This business is 100% risk-free. We look forward to a fruitful business relationship with you. Best Regards Dr. Chima Adams Account Department (NNPC) _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From arcege@speakeasy.net Mon Oct 29 12:44:35 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Mon, 29 Oct 2001 07:44:35 -0500 Subject: [Tutor] String.find won't - why? In-Reply-To: ; from danny.kohn@systematik.se on Mon, Oct 29, 2001 at 12:04:17AM +0100 References: Message-ID: <20011029074435.B984@speakeasy.net> On Mon, Oct 29, 2001 at 12:04:17AM +0100, Danny Kohn wrote: > Am trying to remove all 0D 0A (Hex). Thought this was done through the following while loop. > The file is attached. > The first round things works nicely. The 0D 0A (Hex) is found and removed. Pos is correctly 142. > The second round things behave more strangely. Pos will get a wrong value (178) but there just is no 0D 0A (Hex) there and so the i:pos string will get to short. [other code snipped] > > i=0 > a = '' > while i < len(text): > pos = string.find(text[i:], '\n') > print pos > if pos > 0: > a = a + text[i:pos] > print a > print > i = i + pos + 1 In addition to Remco's comments, the find function also takes an optional third argument which is the starting place. i = 0 a = '' while i < len(text): pos = string.find(text, '\n', i) # now, pos is either -1 or greater than i print pos if pos > 0: a = a + text[i:pos] print a print else: break # no more newlines found i = pos + 1 Since the new position is based on the previous position, we will always get a proper substring (unless you get a -1 ;), this also means that the new position can be used directly for the next time around. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | | Ailment info: http://www.speakeasy.org/~arcege/michaelwatch.html | From alan@mlug.ca Mon Oct 29 14:21:59 2001 From: alan@mlug.ca (Alan Truesdale) Date: Mon, 29 Oct 2001 09:21:59 -0500 Subject: [Tutor] Re: [Tutor] In-Reply-To: References: Message-ID: <01102909215901.15820@caldera.wellconnected.ca> Hi List I'm a lurker on the list just thought I'd post this in regard to the message below. I'm sure you all know its a scam but why take a chance. Nigerian Scam", or the 4-1-9 scam -- named for the fraud section of the Nigerian penal code. >From the Byte article It is one of the more vicious and dangerous of fraud schemes that bilk people all over the world out of hundreds of millions of dollars -- and sometimes, their lives. This scam and other more business-like scams hurt individual but they also hurt the overall image of the Internet as a safe place to do business. More info http://www.byte.com/documents/s=19/byt19990707s0001/index.htm http://www.ustreas.gov/usss/index.htm?alert419.htm&1 On Monday 29 October 2001 05:42 am, you wrote: > FROM THE DESK:Dr.CHIMA ADAMS, > ACCOUNT DEPARTMENT (NNPC) > FALOMO OFFICE COMPLEX, > IKOYI – LAGOS, NIGERIA > TEL:234-8033084103 > FAX: 234-1-7599186 > > > ATTN: GENERAL MANAGER > > Dear Sir, > > I am Dr.Chima Adams chairman- audit committee, with the Nigerian National > Petroleum Corporation (NNPC), I headed the audit committee whose > assignment was to audit, review and recommend payment for all contracts > awarded in the NNPC by the corrupt past military administration. In the > course of our review, we discovered that the sum of USD 30 million (THIRTY > MILLION DOLLARS) was floating unclaimed in the corporation account without > beneficiary. This money emanated from an over-invoicing in the contract > awarded to a foreign firm for the supply, fixing, erecting and computerized > optimization of oil pipeline to one of our oil refineries during the past > Military administration. Base on our status as senior government officials > in top sensitive position of trust, we cannot stand to claim this money > ourselves, hence, I decided to contact you. All modalities for this > transfer have been fully worked out. We have already secured a preliminary > order to effect this payment, we now require from you your BANKING > PARTICULARS, FAX AND TELEPHONE NUMBER for smooth transfer of this money > into your bank account. We intend to share the money in the following > manner: 30% for you, 65% for us and 5% for any miscellaneous expenses. This > business is 100% risk-free. We look forward to a fruitful business > relationship with you. Best Regards > > > Dr. Chima Adams > Account Department (NNPC) > From virketis@fas.harvard.edu Mon Oct 29 18:36:15 2001 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Mon, 29 Oct 2001 13:36:15 -0500 Subject: [Tutor] MySQL and Python Message-ID: <200110291835.f9TIZTH13409@smtp2.fas.harvard.edu> Hi all, I wish to write a Python and MySQL script, which will run on my ISP's server. After checking the Database SIG on python.org, I gathered that one needs the module (http://sourceforge.net/projects/mysql-python) to be installed in order to be able to access a MySQL database from Python. My ISP does not have that module installed, and asked me to provide more information about it. Before I send those guys off installing software on their server, I just want to make sure if this really is the prefered/real way of doing things? Is there some general DB API I can use instead that comes with basic Pyhon? Thanks! Pijus ------------------------------------------------------------ PGP PUBLIC KEY: www.fas.harvard.edu/~virketis/links My weblog: www.fas.harvard.edu/~virketis From boud@valdyas.org Mon Oct 29 18:49:11 2001 From: boud@valdyas.org (Boudewijn Rempt) Date: Mon, 29 Oct 2001 19:49:11 +0100 Subject: [Tutor] MySQL and Python In-Reply-To: <200110291835.f9TIZTH13409@smtp2.fas.harvard.edu> References: <200110291835.f9TIZTH13409@smtp2.fas.harvard.edu> Message-ID: <200110291849.f9TInDj13996@calcifer.valdyas.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Monday 29 October 2001 19:36, Pijus Virketis wrote: > Hi all, > > I wish to write a Python and MySQL script, which will run on my ISP's > server. After checking the Database SIG on python.org, I gathered that = one > needs the module (http://sourceforge.net/projects/mysql-pytho= n) > to be installed in order to be able to access a MySQL database from Pyt= hon. > My ISP does not have that module installed, and asked me to provide mor= e > information about it. Before I send those guys off installing software = on > their server, I just want to make sure if this really is the prefered/r= eal > way of doing things? Is there some general DB API I can use instead tha= t > comes with basic Pyhon? > MySQLdb implements the standard database API for Python - and I certainly prefer to use it. However, you migth also want to investigate an ODBC-bas= ed solution - with mxODBC. I've never used that, though, since I hate introd= ucing extra dependencies (in this case, an ODBC driver for MySQL). - --=20 Boudewijn Rempt | http://www.valdyas.org -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE73aSoN8fj6DnPxOgRAlJrAKCkFGL8q6EBmpaKkB6dx/0tmjeTOQCcC6O+ 9nPweSxd6emV7qKc1Gcbdk0=3D =3D+O5H -----END PGP SIGNATURE----- From david.jay.jackson@wcox.com Mon Oct 29 19:40:15 2001 From: david.jay.jackson@wcox.com (Jackson) Date: Mon, 29 Oct 2001 12:40:15 -0700 Subject: [Tutor] MySQL and Python Message-ID: <200110291240.AA64684286@wcox.com> Can the MySQLdb module be installed into the cgi-bin dir, and called with import /path_to_cgi-bin/MySQLdb ? Just a thought. David ---------- Original Message ---------------------------------- From: Boudewijn Rempt Reply-To: boud@valdyas.org Date: Mon, 29 Oct 2001 19:49:11 +0100 >-----BEGIN PGP SIGNED MESSAGE----- >Hash: SHA1 > >On Monday 29 October 2001 19:36, Pijus Virketis wrote: >> Hi all, >> >> I wish to write a Python and MySQL script, which will run on my ISP's >> server. After checking the Database SIG on python.org, I gathered that one >> needs the module (http://sourceforge.net/projects/mysql-python) >> to be installed in order to be able to access a MySQL database from Python. >> My ISP does not have that module installed, and asked me to provide more >> information about it. Before I send those guys off installing software on >> their server, I just want to make sure if this really is the prefered/real >> way of doing things? Is there some general DB API I can use instead that >> comes with basic Pyhon? >> > >MySQLdb implements the standard database API for Python - and I certainly >prefer to use it. However, you migth also want to investigate an ODBC-based >solution - with mxODBC. I've never used that, though, since I hate introducing >extra dependencies (in this case, an ODBC driver for MySQL). > >- -- > >Boudewijn Rempt | http://www.valdyas.org >-----BEGIN PGP SIGNATURE----- >Version: GnuPG v1.0.6 (GNU/Linux) >Comment: For info see http://www.gnupg.org > >iD8DBQE73aSoN8fj6DnPxOgRAlJrAKCkFGL8q6EBmpaKkB6dx/0tmjeTOQCcC6O+ >9nPweSxd6emV7qKc1Gcbdk0= >=+O5H >-----END PGP SIGNATURE----- > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > From dyoo@hkn.eecs.berkeley.edu Mon Oct 29 20:01:27 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 29 Oct 2001 12:01:27 -0800 (PST) Subject: [Tutor] MySQL and Python In-Reply-To: <200110291835.f9TIZTH13409@smtp2.fas.harvard.edu> Message-ID: On Mon, 29 Oct 2001, Pijus Virketis wrote: > I wish to write a Python and MySQL script, which will run on my ISP's > server. After checking the Database SIG on python.org, I gathered that one > needs the module (http://sourceforge.net/projects/mysql-python) > to be installed in order to be able to access a MySQL database from Python. > My ISP does not have that module installed, and asked me to provide more > information about it. Before I send those guys off installing software on > their server, I just want to make sure if this really is the prefered/real > way of doing things? Is there some general DB API I can use instead that > comes with basic Pyhon? Yes, the MySQLdb module by Andy Dustman, http://dustman.net/andy/python/MySQLdb is the module you'll want if you want to work with Python and MySQL. MySQLdb follows the conventions that most Python database modules follow, the "DB-API 2.0": http://www.python.org/topics/database/DatabaseAPI-2.0.html and so you can use the functions in the API. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Mon Oct 29 20:13:11 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 29 Oct 2001 12:13:11 -0800 (PST) Subject: [Tutor] MySQL and Python In-Reply-To: <200110291240.AA64684286@wcox.com> Message-ID: On Mon, 29 Oct 2001, Jackson wrote: > Can the MySQLdb module be installed into the cgi-bin dir, and called > with import /path_to_cgi-bin/MySQLdb ? We can do something similar to what you're thinking: we can append() the cgi-bin path to the sys.path variable. Once you do this, subsequent imports will also look the cgi-bin directory for modules. Here's an example: Let's say that I have the following files in a personal directory, like "/home/dyoo/src/python": ### [dyoo@tesuque python]$ ls /home/dyoo/src/python dannytest.py test.py ### We can import these modules if we add them to the sys.path: ### >>> import sys >>> print sys.path ['', '/opt/Python-2.1.1/lib/python2.1', '/opt/Python-2.1.1/lib/python2.1/plat-linux2', '/opt/Python-2.1.1/lib/python2.1/lib-tk', '/opt/Python-2.1.1/lib/python2.1/lib-dynload', '/opt/Python-2.1.1/lib/python2.1/site-packages', '/opt/Python-2.1.1/lib/python2.1/site-packages/Numeric'] >>> import dannytest Traceback (most recent call last): File "", line 1, in ? ImportError: No module named dannytest >>> sys.path.append("/home/dyoo/src/python") >>> import dannytest >>> print dannytest.__file__ /home/dyoo/src/python/dannytest.py >>> import test >>> print test.__file__ /opt/Python-2.1.1/lib/python2.1/test/__init__.pyc ### Here, we can see the list of directories that Python scans when we ask it to 'import' things. Note, though, that Python scans the sys.path in order, so if there's a module that's named the same in the standard Python library, that's the one Python will use. That's what's happening above with the "test" module, so be careful. Hope this helps! From 84667-feedback-2@lb.bcentral.com Mon Oct 29 20:17:08 2001 From: 84667-feedback-2@lb.bcentral.com (Aleksandr) Date: 29 Oct 2001 20:17:08 -0000 Subject: [Tutor] ôÏ,ÞÔÏ ÎÅÏÂÈÏÄÉÍÏ ÄÌÑ ÄÏÍÁ,ÓÅÍØÉ,ÄÁÞÉ,ÏÆÉÓÁ,ÐÒÅÄÐÒÉÑÔÉÑ! Message-ID: <1004386628.39301.qmail@ech> kodirovka KOI-8R õ×ÁÖÁÅÍÙÅ ÇÏÓÐÏÄÁ! þÔÏ ÔÁËÏÅ éÎÆÏÒÍÁÃÉÑ ? éÎÆÏÒÍÁÃÉÑ - ÜÔÏ ×ÌÁÓÔØ, ÂÏÇÁÔÓÔ×Ï, ÕÓÐÅÈ, ÐÒÏÃ×ÅÔÁÎÉÅ. ëÔÏ ×ÌÁÄÅÅÔ ÉÎÆÏÒÍÁÃÉÅÊ, ÔÏÔ ÕÐÒÁ×ÌÑÅÔ. éÎÆÏÒÍÁÃÉÑ, ËÏÔÏÒÕÀ ÐÒÅÄÏÓÔÁ×ÌÑÅÔ ÎÁÛÁ ËÏÍÐÁÎÉÑ ÂÕÄÅÔ ÐÏÌÅÚÎÁ, Á × ÏÔÄÅÌØÎÙÈ ÓÌÕÞÁÑÈ É ÐÒÏÓÔÏ ÎÅÏÂÈÏÄÉÍÁ, ËÁË ÏÒÇÁÎÉÚÁÃÉÑÍ, ÐÒÅÄÐÒÉÑÔÉÑÍ, ÔÁË É ËÁÖÄÏÍÕ ÞÅÌÏ×ÅËÕ É ÅÇÏ ÓÅÍØÅ. 1. ÷ÓÅ ÍÙ ÚÎÁÅÍ ÓÌÏ×Á <ÇÏÒÎÙÊ ×ÏÚÄÕÈ>, ÎÏ ÎÁ×ÅÒÎÏÅ ÎÅ ×ÓÅ ÚÎÁÀÔ, ÞÔÏ ÅÇÏ ÃÅÌÅÂÎÙÅ Ó×ÏÊÓÔ×Á ÚÁ×ÉÓÑÔ ÎÅ ÔÏÌØËÏ ÏÔ ÏÔÓÕÔÓÔ×ÉÑ ×ÒÅÄÎÙÈ ÐÒÉÍÅÓÅÊ, ÎÏ É ÏÔ ÎÁÌÉÞÉÑ ÔÁË ÎÁÚÙ×ÁÅÍÙÈ <ÏÔÒÉÃÁÔÅÌØÎÙÈ ÉÏÎÏ×> ÉÌÉ ÁÜÒÏÉÏÎÏ×(áé) ËÉÓÌÏÒÏÄÁ. äÅÑÔÅÌØÎÏÓÔØ "ÃÉ×ÉÌÉÚÏ×ÁÎÎÏÇÏ ÞÅÌÏ×ÅÞÅÓÔ×Á", ÒÁÚ×ÉÔÉÅ ÐÒÏÉÚ×ÏÄÓÔ× Ó ÐÏÑ×ÌÅÎÉÅÍ ÇÉÇÁÎÔÓËÉÈ "ÓÍÏÇÏ×" ÐÒÉ×ÅÌÉ Ë ÒÅÚËÏÍÕ ÕÍÅÎØÛÅÎÉÀ ËÏÌÉÞÅÓÔ×Á <ÏÔÒÉÃÁÔÅÌØÎÙÈ ÉÏÎÏ×> × ×ÏÚÄÕÈÅ. ÷ÏÚÄÕÈ ÎÁÛÉÈ ÖÉÌÙÈ ÐÏÍÅÝÅÎÉÊ ÂÉÏÌÏÇÉÞÅÓËÉ ÍÅÒÔ×ÙÊ. äÌÑ ÓÒÁ×ÎÅÎÉÑ: × ÇÏÒÁÈ áÂÈÁÚÉÉ (ÇÄÅ ÂÏÌØÛÅ ×ÓÅÇÏ ÄÏÌÇÏÖÉÔÅÌÅÊ) ËÏÌÉÞÅÓÔ×Ï ÏÔÒÉÃÁÔÅÌØÎÙÈ ÁÜÒÏÉÏÎÏ× ÏËÏÌÏ 20 000 × 1 ËÕÂ. ÓÍ ×ÏÚÄÕÈÁ, × ÍÏÒÓËÏÍ ×ÏÚÄÕÈÅ ÉÈ 2 000, × ÚÅÌÅÎÏÍ ÖÅ ÍÁÓÓÉ×Å ÓÒÅÄÎÅÊ ÐÏÌÏÓÙ òÏÓÓÉÉ - 200-1000, × ÐÒÏÉÚ×ÏÄÓÔ×ÅÎÎÙÈ ÐÏÍÅÝÅÎÉÑÈ ×ÓÅÇÏ 10-20, Á ÐÅÒÅÄ ÜËÒÁÎÏÍ ÔÅÌÅ×ÉÚÏÒÁ ÉÌÉ ËÏÍÐØÀÔÅÒÁ - ÁÂÓÏÌÀÔÎÙÊ 0. ðÏ ÓÁÎÉÔÁÒÎÙÍ ÎÏÒÍÁÍ íú óóóò ÕÒÏ×ÅÎØ ËÏÎÃÅÎÔÒÁÃÉÉ ÁÜÒÏÉÏÎÏ×, ÏÔËÌÏÎÅÎÉÅ ÏÔ ËÏÔÏÒÏÇÏ ÓÏÚÄÁÅÔ ÕÇÒÏÚÕ ÚÄÏÒÏ×ØÀ ÞÅÌÏ×ÅËÁ - ÎÁÈÏÄÉÔÓÑ × ÄÉÁÐÁÚÏÎÅ ÏÔ 600 áé ÄÏ 50000 áé × ËÕÂ.ÓÍ.!!!!! ÷ÓÅ ÜÔÏ ÐÒÉ×ÏÄÉÔ Ë ÂÏÌÅÚÎÑÍ, ÏÓÌÁÂÌÅÎÉÀ ÉÍÕÎÉÔÅÔÁ, ÓÏËÒÁÝÅÎÉÀ ÖÉÚÎÉ. ÷ÎÅÛÎÉÅ ÆÁËÔÏÒÙ ÚÁÝÉÔÙ ÕÖÅ ÎÅ ÐÏÍÏÇÁÀÔ. ôÒÅÂÕÅÔÓÑ ×ÍÅÛÁÔÅÌØÓÔ×Ï ÉÓËÕÓÓÔ×ÅÎÎÙÍ ÐÕÔÅÍ. é ÚÄÅÓØ ×ÁÖÎÕÀ ÒÏÌØ ÍÏÇÕÔ ÓÙÇÒÁÔØ ÉÓËÕÓÓÔ×ÅÎÎÙÅ ÇÅÎÅÒÁÔÏÒÙ ÏÔÒÉÃÁÔÅÌØÎÙÈ ÁÜÒÏÉÏÎÏ× - ÁÜÒÏÉÏÎÉÚÁÔÏÒÙ ÉÌÉ ËÁË ÉÈ ÅÝÅ ÎÁÚÙ×ÁÀÔ - "ìÀÓÔÒÙ þÉÖÅ×ÓËÏÇÏ". ïÎÉ ÓÏÚÄÁÀÔ ÄÏÓÔÁÔÏÞÎÕÀ ÄÌÑ ÖÉÚÎÅÎÎÙÈ ÐÒÏÃÅÓÓÏ× ËÏÎÃÅÎÔÒÁÃÉÀ ÏÔÒÉÃÁÔÅÌØÎÙÈ ÁÜÒÏÉÏÎÏ×, ÐÏÒÑÄËÁ 20 000 - 30 000 × 1 ËÕÂ.ÓÍ, ÉÍÉÔÉÒÕÑ ÕÓÌÏ×ÉÑ ÇÏÒÎÏÊ ÍÅÓÔÎÏÓÔÉ ÉÌÉ þÅÒÎÏÍÏÒÓËÏÇÏ ÐÏÂÅÒÅÖØÑ ëÒÙÍÁ ÉÌÉ ëÁ×ËÁÚÁ. ÷ ÜÔÉÈ ÕÓÌÏ×ÉÑÈ ÞÅÌÏ×ÅË ÉÓÐÙÔÙ×ÁÅÔ ËÏÍÆÏÒÔÎÏÅ ÓÏÓÔÏÑÎÉÅ, ÐÒÉÏÂÒÅÔÁÅÔ ÚÄÏÒÏ×ØÅ É ÐÒÏÄÌÑÅÔ ÓÅÂÅ ÖÉÚÎØ. îÁÛÁ ÏÒÇÁÎÉÚÁÃÉÑ ÐÒÏÄÁ£Ô ÄÁÎÎÙÅ ÌÀÓÔÒÙ (ÞÅÔÙÒÅ ÍÏÄÅÌÉ) ÓÏÂÒÁÎÎÙÅ ÎÅÐÏÓÒÅÄÓÔ×ÅÎÎÏ ÐÏ ÞÅÒÔÅÖÁÍ ÓÁÍÏÇÏ á.ì. þÉÖÅ×ÓËÏÇÏ ÏÐÔÏÍ É × ÒÏÚÎÉÃÕ. ï ÚÄÏÒÏ×ØÅ ÎÅÏÂÈÏÄÉÍÏ ÚÁÂÏÔÉÔØÓÑ ÓÅÊÞÁÓ, ÎÅ ÏÔËÌÁÄÙ×ÁÑ ÎÁ ÐÏÔÏÍ. ÷ÅÄØ, ËÁË ÉÚ×ÅÓÔÎÏ ÚÄÏÒÏ×ØÅ ÎÅ ËÕÐÉÛØ. ÷ÓÑ ÉÎÆÏÒÍÁÃÉÑ Ï ÔÏ×ÁÒÁÈ ÎÁÛÅÊ ËÏÍÐÁÎÉÉ ÎÁ ÓÁÊÔÅ: www.viel.f2s.com 2. íÙ ÐÒÅÄÌÁÇÁÅÍ ÎÁÄÅÖÎÕÀ ÚÁÍÅÎÕ ÜÌÅËÔÒÉÞÅÓËÉÍ ÞÁÊÎÉËÁÍ -ÁÐÐÁÒÁÔÙ ÄÌÑ ÎÁÇÒÅ×Á É ÏÈÌÁÖÄÅÎÉÑ ÐÉÔØÅ×ÏÊ ×ÏÄÙ( ËÕÌÅÒÙ), Á ÔÁËÖÅ ÁÐÐÁÒÁÔÙ ÇÁÚ×ÏÄÙ ÄÌÑ <ÇÏÒÑÞÉÈ> ÃÅÈÏ× É ÐÒÅÄÐÒÉÑÔÉÊ(á÷-2,á÷-3,POST-MIX É ÄÒ). ëÕÌÅÒÙ-ÏÞÅÎØ ÕÄÏÂÎÙ ÐÒÉ ÉÓÐÏÌØÚÏ×ÁÎÉÉ × ÏÆÉÓÁÈ , ÇÄÅ ÏÎÉ ÂÅÓÐÅÒÅÂÏÊÎÏ ÏÂÅÓÐÅÞÉ×ÁÀÔ ÈÏÌÏÄÎÏÊ ×ÏÄÏÊ ÉÌÉ ÇÏÒÑÞÉÍÉ ÎÁÐÉÔËÁÍÉ. ïÎÉ ÓÏ×ÍÅÝÁÀÔ ÆÕÎËÃÉÉ ÞÁÊÎÉËÁ É ÏÈÌÁÄÉÔÅÌÑ, ÐÏÚ×ÏÌÑÀÝÉÅ ÍÇÎÏ×ÅÎÎÏ ×ÏÓÐÏÌØÚÏ×ÁÔØÓÑ ÇÏÒÑÞÅÊ ÉÌÉ ÈÏÌÏÄÎÏÊ ÐÉÔØÅ×ÏÊ ×ÏÄÏÊ. üÔÏ ÚÎÁÞÉÔÅÌØÎÏ ÏÂÌÅÇÞÁÅÔ ÐÒÉÇÏÔÏ×ÌÅÎÉÅ ÞÁÑ, ËÏÆÅ, ÒÁÓÔ×ÏÒÉÍÙÈ ÓÕÐÏ×, Á ÔÁËÖÅ ÏÈÌÁÖÄÅÎÎÙÈ ÎÁÐÉÔËÏ×. îÁÞÁ× ÐÏÌØÚÏ×ÁÔØÓÑ ÎÁÛÉÍÉ ÁÐÐÁÒÁÔÁÍÉ × ÂÙÔÕ É ÎÁ ÒÁÂÏÔÅ, ×Ù ÎÅ ×ÅÒÎÅÔÅÓØ Ë ÐÏÌØÚÏ×ÁÎÉÀ ÞÁÊÎÉËÏÍ É ×ÏÄÏÊ ÉÚ ÐÏÄ ËÒÁÎÁ. îÁÓÔÏÌØÎÙÅ ÍÏÄÅÌÉ ÉÄÅÁÌØÎÏ ÐÏÄÈÏÄÑÔ ÄÌÑ ÄÏÍÁÛÎÅÇÏ ÉÓÐÏÌØÚÏ×ÁÎÉÑ. ïÎÉ ÎÅ ÚÁÎÉÍÁÀÔ ÍÎÏÇÏ ÍÅÓÔÁ É ÐÒÅËÒÁÓÎÏ ×ÐÉÓÙ×ÁÀÔÓÑ × ÉÎÔÅÒØÅÒ ÓÏ×ÒÅÍÅÎÎÏÊ ËÕÈÎÉ. óÎÉÖÁÅÔÓÑ ÒÁÓÈÏÄ ÜÌÅËÔÒÏÜÎÅÒÇÉÉ - ÎÁÇÒÅ× ×ÏÄÕ, ËÕÌÅÒ Á×ÔÏÍÁÔÉÞÅÓËÉ ÐÅÒÅËÌÀÞÁÅÔÓÑ × ÒÅÖÉÍ ÏÖÉÄÁÎÉÑ É ×ËÌÀÞÉÔ ÎÁÇÒÅ× ÓÎÏ×Á, ËÏÇÄÁ ÔÅÍÐÅÒÁÔÕÒÁ ×ÏÄÙ × ÔÅÒÍÏÓÅ ÏÐÕÓÔÉÔÓÑ ÄÏ 85œó.. 3. ïÂÌÁÓÔØ ÜÌÅËÔÒÏÎÉËÉ, ÜÔÏ ÎÅ ÔÏÌØËÏ ÐÏÓÔÁ×ËÉ ÐÒÉÂÏÒÏ×, ÁÐÐÁÒÁÔÕÒÙ, ÎÏ É ÒÁÚÌÉÞÎÙÅ ËÏÍÐÌÅËÔÕÀÝÉÅ ËÁË ÏÔÅÞÅÓÔ×ÅÎÎÙÈ, ÔÁË É ÚÁÒÕÂÅÖÎÙÈ ÐÒÏÉÚ×ÏÄÉÔÅÌÅÊ ÜÌÅËÔÒÏÎÎÏÊ ÔÅÈÎÉËÉ. üÔÏ ÔÁËÉÅ ÆÉÒÍÙ ËÁË International Rectifier, Epcos,Bourns, Metex, unit-t É ÄÒ. 4. ó×ÁÒÏÞÎÙÅ ÜÌÅËÔÒÏÄÙ: ÍÙ ÐÒÏÄÁ£Í ÜÌÅËÔÒÏÄÙ ÏÔ ×ÅÄÕÝÉÈ ÏÔÅÞÅÓÔ×ÅÎÎÙÈ ÐÒÏÉÚ×ÏÄÉÔÅÌÅÊ. ÷ÓÅ Ó×ÁÒÏÞÎÙÅ ÜÌÅËÔÒÏÄÙ ÓÏÏÔ×ÅÔÓÔ×ÕÀÔ çïóôÕ É ÉÍÅÀÔ ÓÅÒÔÉÆÉËÁÔ ËÁÞÅÓÔ×Á. ôÁËÖÅ ÍÙ ÐÒÅÄÌÁÇÁÅÍ è/ë É ç/ë ÌÉÓÔÏ×ÏÊ ÍÅÔÁÌÌÏÐÒËÁÔ. ÷ ÎÁÓÔÏÑÝÅÅ ×ÒÅÍÑ ÍÙ ÐÒÅÄÌÁÇÁÅÍ ÕÎÉËÁÌØÎÕÀ ÒÁÚÒÁÂÏÔËÕ ÏÔÅÞÅÓÔ×ÅÎÎÙÈ ÕÞÅÎÙÈ: ËÏÍÐÅÎÓÉÒÕÀÝÉÅ ÐÁÔÒÕÂËÉ ÄÌÑ ÂÅÚÓ×ÁÒÎÏÇÏ ÓÏÅÄÉÎÅÎÉÑ ÍÅÔÁÌÌÉÞÅÓËÉÈ ÔÒÕÂ!!!(D ÏÔ 25 ÄÏ 1000ÍÍ.) îÁÛÉ ÍÅÎÅÄÖÅÒÙ ÉÍÅÀÔ ÂÏÇÁÔÙÊ ÏÐÙÔ ÐÒÏÄÁÖ, ÍÁÒËÅÔÉÎÇÏ×ÙÈ ÉÓÓÌÅÄÏ×ÁÎÉÊ, ×ÅÄÅÎÉÑ ÐÅÒÅÇÏ×ÏÒÏ× Ó ËÒÕÐÎÙÍÉ ÐÏÓÔÁ×ÝÉËÁÍÉ É ÐÏÔÒÅÂÉÔÅÌÑÍÉ ÔÏ×ÁÒÏ×, ÞÔÏ ÐÏÚ×ÏÌÑÅÔ ÎÁÍ ÄÏÓÔÁÔØ ÎÕÖÎÕÀ ÷ÁÍ ÐÒÏÄÕËÃÉÀ ÐÏ ×ÙÇÏÄÎÙÍ ÄÌÑ ÷ÁÓ ÃÅÎÁÍ É × ÏÐÔÉÍÁÌØÎÏ ËÏÒÏÔËÉÅ ÓÒÏËÉ. òÁÓÓÍÏÔÒÉÍ ÉÎÔÅÒÅÓÎÙÅ ÐÒÅÄÌÏÖÅÎÉÑ(ÐÏ ÐÒÉÅÍÌÅÍÙÍ, ËÏÎËÕÒÉÒÕÀÝÉÍ ÃÅÎÁÍ)ÓÂÙÔÁ ÐÒÏÄÕËÃÉÉ ÷ÁÛÅÇÏ ÐÒÅÄÐÒÉÑÔÉÑ, Á ÔÁËÖÅ ×ÏÚÍÏÖÅÎ ×ÁÒÉÁÎÔ ÒÁÓÓÍÏÔÒÅÎÉÑ ÐÏÓÔÁ×ËÉ ÔÏ×ÁÒÏ×, ËÏÔÏÒÙÅ ÎÅ ×ÏÛÌÉ × ÓÆÅÒÕ ÄÅÑÔÅÌØÎÏÓÔÉ ÎÁÛÅÊ ÏÒÇÁÎÉÚÁÃÉÉ!!! ÷ÁÛÕ ÐÏÔÒÅÂÎÏÓÔØ, ÍÏÖÎÏ ÏÔÐÒÁ×ÉÔØ ÎÁ ÎÁÛ ÆÁËÓ:(095) 275-89-94, ÉÌÉ ÐÏ ÜÌÅËÔÒÏÎÎÏÊ ÐÏÞÔÅ: vielmm@yahoo.com íÙ ÖÄÅÍ ÷ÁÓ É ×ÙÒÁÖÁÅÍ Õ×ÅÒÅÎÎÏÓÔØ × ÔÏÍ, ÞÔÏ ÏÂÒÁÔÉ×ÛÉÓØ Ë ÎÁÍ, ÷Ù ÐÏÌÕÞÉÔÅ Ë×ÁÌÉÆÉÃÉÒÏ×ÁÎÎÕÀ ÐÏÍÏÝØ, ×ÎÉÍÁÔÅÌØÎÏÅ ÏÔÎÏÛÅÎÉÅ Ë ÷ÁÛÉÍ ÐÏÔÒÅÂÎÏÓÔÑÍ, ÏÐÅÒÁÔÉ×ÎÕÀ ÏÂÒÁÂÏÔËÕ ÷ÁÛÅÇÏ ÚÁËÁÚÁ. ðÏ ×ÓÅÍ ×ÏÐÒÏÓÁÍ ×Ù ÍÏÖÅÔÅ ÏÂÒÁÝÁÔØÓÑ ÐÏ ÔÅÌÅÆÏÎÁÍ × Ç. íÏÓË×Á: (095) 275-89-94,746-68-78 _______________________________________________________________________ Powered by List Builder To unsubscribe follow the link: http://lb.bcentral.com/ex/manage/subscriberprefs?customerid=15920&subid=1D33251A78989F23&msgnum=2 From printers@sendme.cz Thu Oct 18 10:39:59 2001 From: printers@sendme.cz (A) Date: Thu, 18 Oct 2001 11:39:59 +0200 Subject: [Tutor] Python script engine Message-ID: <3BCEBF8F.32176.90A37A@localhost> Hello, In my application I would like to allow users to add/use basic python commands but I do not want users to change my code of application directly. For example my program expects telephone. number in format +442076812563 but a user sometimes may want to supply 0044 207 681 2563 (please note a blank). Then the user would need to use STRING.JOIN Python function to get from the user's input (0044 207 681 2563) the string that my program expects (+442076812563) Does anyone have any idea how to do that? Thank you for help Ladislav _______________________________________________ ActivePython mailing list ActivePython@listserv.ActiveState.com http://listserv.ActiveState.com/mailman/listinfo/activepython From discuss@sendme.cz Sat Oct 20 22:41:34 2001 From: discuss@sendme.cz (A) Date: Sat, 20 Oct 2001 23:41:34 +0200 Subject: [Tutor] Re:Python script engine - Thanks Message-ID: <3BD20BAE.9563.7693B3@localhost> I would like to thank you all that answered my question. Execfile() will do all that I need. Thanks. Ladislav _______________________________________________ ActivePython mailing list ActivePython@listserv.ActiveState.com http://listserv.ActiveState.com/mailman/listinfo/activepython From printers@sendme.cz Mon Oct 8 09:54:22 2001 From: printers@sendme.cz (A) Date: Mon, 8 Oct 2001 10:54:22 +0200 Subject: [Tutor] DNS module or how to ... ? Message-ID: <3BC185DE.30945.6E5441@localhost> Hello, Is there a DNS module available for Python ? Or is there a method how I can , from my python program, find out an email server for a particular domain? For example for email printers@sendme.cz I find out that email server mail.contactel.cz serves for domain sendme.cz Thank you for help. Ladislav _______________________________________________ ActivePython mailing list ActivePython@listserv.ActiveState.com http://listserv.ActiveState.com/mailman/listinfo/activepython From discuss@sendme.cz Sat Oct 20 22:41:34 2001 From: discuss@sendme.cz (A) Date: Sat, 20 Oct 2001 23:41:34 +0200 Subject: [Tutor] Smtplib module Message-ID: <3BD20BAE.6346.7693E0@localhost> Hi, I want to use smtplib module for sending emails. Is there any way how I can test a return code, generated by this module, to see if an email was accepting for delivery, for example? Thank you for help. _______________________________________________ ActivePython mailing list ActivePython@listserv.ActiveState.com http://listserv.ActiveState.com/mailman/listinfo/activepython From szilard@int.com Mon Oct 29 22:20:36 2001 From: szilard@int.com (Szilard Bokros) Date: Mon, 29 Oct 2001 16:20:36 -0600 Subject: [Tutor] computer game Message-ID: <3BDDD634.B6084B3E@int.com> Hello, is there any cool python computer game around? I prefer strategy games, wargames. I haven't seen anything yet, but I will be surprized if there wasnt any. Does anyone know about a collection of python based games? Szilard From dsh8290@rit.edu Mon Oct 29 23:05:01 2001 From: dsh8290@rit.edu (dman) Date: Mon, 29 Oct 2001 18:05:01 -0500 Subject: [Tutor] Re: How to change Windows Environment Variable In-Reply-To: ; from ignacio@openservices.net on Thu, Aug 30, 2001 at 08:14:06PM -0400 References: Message-ID: <20011029180501.A3928@harmony.cs.rit.edu> On Thu, Aug 30, 2001 at 08:14:06PM -0400, Ignacio Vazquez-Abrams wrote: | On Fri, 31 Aug 2001, ??? wrote: | | > Dear all, | > | > How to change environment variable on Windows NT or 2000 by python? | > | > In Visual Basic case can setting as below: | > | > Private Declare Function GetEnvironmentVariable Lib "kernel32" _ | > Alias "GetEnvironmentVariableA" (ByVal lpName As String, _ | > ByVal lpBuffer As String, ByVal nSize As Long) As Long | > | > Private Declare Function SetEnvironmentVariable Lib "kernel32" _ | > Alias "SetEnvironmentVariableA" (ByVal lpName As String, _ | > ByVal lpValue As String) As Long | > | > I will waiting for good news. | > Thanks. | > MyeongKi Han | | Good news: | | There is a GetEnvironmentVariable() function in the win32api module. | | Bad news: | | There is no SetEnvironmentVariable() function. See the 'os' module. >>> import os >>> print os.putenv.__doc__ putenv(key, value) -> None Change or add an environment variable. >>> The 'os.environ' attribute is a dict containing all the environment variables. -D From kauphlyn@speakeasy.org Mon Oct 29 23:15:04 2001 From: kauphlyn@speakeasy.org (Daniel Coughlin) Date: Mon, 29 Oct 2001 15:15:04 -0800 (PST) Subject: [Tutor] computer game In-Reply-To: <3BDDD634.B6084B3E@int.com> Message-ID: Check out http://pygame.org I have played a few of these games and have found that most are buggy at best and not particularly cool. The cool part comes from them being written in python. The ones that I played had an early eighties intellivision feel to them. Hope this helps. Daniel On Mon, 29 Oct 2001, Szilard Bokros wrote: > Hello, > is there any cool python computer game around? > I prefer strategy games, wargames. I haven't seen anything yet, > but I will be surprized if there wasnt any. > Does anyone know about a collection of python based games? > Szilard > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From joejava@dragoncat.net Tue Oct 30 00:51:24 2001 From: joejava@dragoncat.net (Joel Ricker) Date: Mon, 29 Oct 2001 19:51:24 -0500 Subject: [Tutor] Python performance on Windows system References: <002701c15ea3$cdb33ac0$98a0d6d1@joeltklrijxxms> <3BDBECE0.6900EBDD@chello.nl> Message-ID: <003101c160dd$00dd8140$7fa1d6d1@joeltklrijxxms> ----- Original Message ----- From: "Roeland Rengelink" > Without further ado, here's a class (bitset) that packs the information > you're interested in. It uses the fact that an integer contains 32 bits. > So I can store n bits of information in an array of n/32 integers. I > also include a version of your sieve algorithm that uses the bitset to > store its result. All I can say is wow! 1 to 10 million ran in a matter of minutes as opposed to several hours -- not sure how long as I haven't had the patience to let the script suck up that much system resources as I mentioned before. I ran 1 to 50 million while I was at work. Not sure how long it took but it was finished when I got home and ran nicely with my Prime95 program (distributed project to find next largest merseinne prime). In the back of my mind I thought that the use of binary numbers to pack information would be a better way to go and as I can see I was right. My problem is that its just an idea -- I don't quite know how to implement effectively binary constructs to store data. I know how binary numbers work (ie 010 = 2, 1111 = 15) and thats it -- all the comp sci classes I've ever taken never went into detail as to how to use them. >> and << operators mean really nothing to me. I've seen them used in code before especially mathematical computations and would like to learn more. Can anyone recommend any resources of study either online or book form that covers this topic thoroughly? Thanks Joel From dyoo@hkn.eecs.berkeley.edu Tue Oct 30 01:07:36 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 29 Oct 2001 17:07:36 -0800 (PST) Subject: [Tutor] Python performance on Windows system In-Reply-To: <003101c160dd$00dd8140$7fa1d6d1@joeltklrijxxms> Message-ID: On Mon, 29 Oct 2001, Joel Ricker wrote: > In the back of my mind I thought that the use of binary numbers to > pack information would be a better way to go and as I can see I was > right. My problem is that its just an idea -- I don't quite know how > to implement effectively binary constructs to store data. I know how > binary numbers work (ie 010 = 2, 1111 = 15) and thats it -- all the > comp sci classes I've ever taken never went into detail as to how to > use them. >> and << operators mean really nothing to me. I've seen > them used in code before especially mathematical computations and > would like to learn more. Can anyone recommend any resources of study > either online or book form that covers this topic thoroughly? The book "Structure and Interpretation of Computer Programs" has an example on finding prime numbers using a probabilistic method: http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%25_sec_1.2.6 However, if you look at the link, you'll find that all the source code looks... umm... really parenthesized. *grin* They use a programming language called Scheme for their demonstrations, but their also explain the theory behind the code, so you should be able to get some ideas from it. If someone has time, perhaps he or she can translate some of the source code from Scheme to Python? For example, SICP's method on the "expmod", the exponential of a number modulo another number: ;;; (define (expmod base exp m) (cond ((= exp 0) 1) ((even? exp) (remainder (square (expmod base (/ exp 2) m)) m)) (else (remainder (* base (expmod base (- exp 1) m)) m)))) ;;; has a somewhat close translation in Python: ### def square(x): return x * x def isEven(x): return x % 2 == 0 def expmod(base, exp, m): if exp == 0: return 1 if isEven(exp): return square(expmod(base, exp/2, m) % m) return base * expmod(base, exp - 1, m) % m ### But it sounds like you've interested in mathematics; if so, SICP is an excellent book to take a look at... even if it doesn't use Python... *grin* Good luck to you. From ylee12@uiuc.edu Tue Oct 30 01:47:35 2001 From: ylee12@uiuc.edu (Young-Jin Lee) Date: Mon, 29 Oct 2001 19:47:35 -0600 Subject: [Tutor] [Q] Python, Jython, and drawing application Message-ID: <010a01c160e4$d8f83640$95757e82@visit2> This is a multi-part message in MIME format. ------=_NextPart_000_0107_01C160B2.8E3F41C0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, I'm new to Python programming and I have a question. If I make a Jython application, can the Jython application use the Java = application? I have a Java application and I want to switch my programming language = to Python, but I don't want to dump my Java application. If it's = possible, how can I do it? Any good tutorials? How about performance? I have read the Python tutorial and I felt like Python is most focusing = a server programming. (Relatively little documentation and tutorial on = GUI exists.) How difficult would it be to develop a petri net drawing or = a UML drawing application?=20 Is there any example code for these kinds of python application? Thanks in advance. Young-Jin Lee ------=_NextPart_000_0107_01C160B2.8E3F41C0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi, I'm new to Python programming and I = have a=20 question.
If I make a Jython application, can the = Jython=20 application use the Java application?
I have a Java application and I want to = switch my=20 programming language to Python, but I don't want to dump my Java = application. If=20 it's possible, how can I do it? Any good tutorials? How about=20 performance?
 
I have read the Python tutorial and I = felt like=20 Python is most focusing a server programming. (Relatively little documentation and tutorial on GUI exists.) = How=20 difficult would it be to develop a petri net drawing or a UML drawing=20 application?
Is there any example code for these = kinds of python=20 application?
 
Thanks in advance.
 
Young-Jin = Lee
------=_NextPart_000_0107_01C160B2.8E3F41C0-- From dsh8290@rit.edu Tue Oct 30 03:04:35 2001 From: dsh8290@rit.edu (dman) Date: Mon, 29 Oct 2001 22:04:35 -0500 Subject: [Tutor] [Q] Python, Jython, and drawing application In-Reply-To: <010a01c160e4$d8f83640$95757e82@visit2>; from ylee12@uiuc.edu on Mon, Oct 29, 2001 at 07:47:35PM -0600 References: <010a01c160e4$d8f83640$95757e82@visit2> Message-ID: <20011029220435.A4524@harmony.cs.rit.edu> On Mon, Oct 29, 2001 at 07:47:35PM -0600, Young-Jin Lee wrote: | Hi, I'm new to Python programming and I have a question. | If I make a Jython application, can the Jython application use the | Java application? Yes. | I have a Java application and I want to switch my programming | language to Python, but I don't want to dump my Java application. If | it's possible, how can I do it? Any good tutorials? How about | performance? Simply run your code with Jython. Here's an example : ------ jy.py ---- import javax frame = javax.swing.JFrame() frame.getContentPane().add( javax.swing.JLabel( "hello" ) ) frame.setSize( 100 , 100 ) frame.setVisible( 1 ) --------------- $ jython jy.py | I have read the Python tutorial and I felt like Python is most | focusing a server programming. (Relatively little documentation and | tutorial on GUI exists.) There are many different GUI toolkits available for use in a python application. The tutorial doesn't talk about it because the tutorial focuses on the python language, and not any libraries for it. The details of using a particular toolkit are found in the documentation for that toolkit. If you are writing a pure python application, and using the C interpreter, you can use GTK+/GNOME Qt/KDE wxPython Tkinter MSW (on Windows only) Fox PMW V (others?) If you use jython, you are limited to the toolkits supported by java. This includes AWT Swing GTK+/GNOME (uses JNI) Tkinter (Finn created bindings, but I don't know if they are curren) MSW (iff you use MS's JVM and COM) | How difficult would it be to develop a | petri net drawing I don't know what that is. | or a UML drawing application? I think it would be easier than with Java. However, such apps already exist (xfig, dia) so it may suffice for you to use one of these. If your goal is to practice programming, then go ahead and create another one. HTH, -D From dyoo@hkn.eecs.berkeley.edu Tue Oct 30 04:26:44 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 29 Oct 2001 20:26:44 -0800 (PST) Subject: [Tutor] DNS module or how to ... ? In-Reply-To: <3BC185DE.30945.6E5441@localhost> Message-ID: On Mon, 8 Oct 2001, A wrote: > Is there a DNS module available for Python ? There are a few resources you can use if you're looking for Python modules. One of the best ones is the Vaults of Parnassus: http://www.vex.net/parnassus/ which collects links for a bunch of stuff. http://www.vex.net/parnassus/apyllo.py?find=dns lists the entries associated with DNS. Good luck to you! From dyoo@hkn.eecs.berkeley.edu Tue Oct 30 05:09:46 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 29 Oct 2001 21:09:46 -0800 (PST) Subject: [Tutor] [Q] Python, Jython, and drawing application In-Reply-To: <010a01c160e4$d8f83640$95757e82@visit2> Message-ID: On Mon, 29 Oct 2001, Young-Jin Lee wrote: > Hi, I'm new to Python programming and I have a question. I hope you are having a fun time with Python so far. > If I make a Jython application, can the Jython application use the > Java application? I have a Java application and I want to switch my Yes, this is one of the really neat things about Jython: all the Java classes look as though they were Python classes. Here's an example: ### [dyoo@tesuque dyoo]$ jython Jython 2.1a3 on java1.3.0_02 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> import java >>> mylist = java.util.ArrayList() >>> mylist.add("Hello") 1 >>> mylist.add(" ") 1 >>> mylist.add("world") 1 >>> mylist [Hello, , world] ### > programming language to Python, but I don't want to dump my Java > application. If it's possible, how can I do it? Any good tutorials? The Jython web site, http://jython.org/ has tutorials on getting Jython working. You might also want to ask the Jython mailing list for more information particular to Jython: http://lists.sourceforge.net/lists/listinfo/jython-users > How about performance? Err... I wouldn't touch that question with a flagpole. *grin* > I have read the Python tutorial and I felt like Python is most > focusing a server programming. (Relatively little documentation and > tutorial on GUI exists.) How difficult would it be to develop a petri There's actually a LOT of documentation on GUI interfaces, if just not well advertised... *grin* You'll definitely want to look at: http://python.org/topics/tkinter/ which is the main "Topics" corner for Tkinter stuff. This page has a link to a very nice tutorial on the Tkinter GUI interface here: http://www.pythonware.com/library/tkinter/introduction/index.htm Moreover, Cameron Laird has accumulated a lot of information on Python GUI's: http://starbase.neosoft.com/~claird/comp.lang.python/python_GUI.html which tries to catalog all the GUIs developed for Python. A bit overwhelming, but nice to know about. Finally, there's an article on IBM developerworks that touches on a universal 'anygui' module that tries to unify the gui frameworks: http://www-106.ibm.com/developerworks/linux/library/l-anygui/ and the resources at the bottom of this article might be useful for you. > net drawing or a UML drawing application? Is there any example code > for these kinds of python application? Dunno about this one. If you have more questions, please feel free to ask! From kimtitu@yahoo.com Tue Oct 30 05:27:16 2001 From: kimtitu@yahoo.com (Titu Kim) Date: Mon, 29 Oct 2001 21:27:16 -0800 (PST) Subject: [Tutor] Can someone help me to improve this segment? Message-ID: <20011030052716.18291.qmail@web14707.mail.yahoo.com> Hi, I am little obssessed with my own coded after i found out it is slow. I am trying to construct a html table string from a result that i obtain from database.My code segment look like this: assume result holds 2D list. ******* method******************************** def f1(item): return ""+str(item)+"" ***************************************** ************main program piece*********** tab = "\n" for x in result: tab = tab + "" tab = tab + string.join(map(f1,x),"")+"\n" tab = tab + "
" ********************************************** Can anyone improve this code segment? Thanks alot Regards, Kim Titu __________________________________________________ Do You Yahoo!? Make a great connection at Yahoo! Personals. http://personals.yahoo.com From dyoo@hkn.eecs.berkeley.edu Tue Oct 30 05:59:41 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 29 Oct 2001 21:59:41 -0800 (PST) Subject: [Tutor] Can someone help me to improve this segment? In-Reply-To: <20011030052716.18291.qmail@web14707.mail.yahoo.com> Message-ID: Hi Titu, welcome to Tutor! On Mon, 29 Oct 2001, Titu Kim wrote: > I am little obssessed with my own coded after i found out it is slow. That's ok; Optimizing programs is a good goal as long as you know where to pinpoint your efforts. > I am trying to construct a html table string from a result that i > obtain from database.My code segment look like this: assume result > holds 2D list. > > ******* method******************************** > def f1(item): > return ""+str(item)+"" > ***************************************** > ************main program piece*********** > tab = "\n" > for x in result: > tab = tab + "" > tab = tab + string.join(map(f1,x),"")+"\n" > tab = tab + "
" I think that the string concatenating may be the culprit: it's somewhat expensive to do a lot of small string concatentations. For example: ### >>> numbers = map(str, range(100000)) >>> mystr = "" >>> for element in numbers: ... mystr = mystr + str(element) ... ### causes my computer to grind to a halt: Python spends a lot of time trying to put things together, and it just fumbles. Imagine someone writing a word on a chalkboard, erasing it, writing it again, erasing it, writing it again... that's a handwavy way of seeing that doing concatenation like this is expensive. What Python's better at is taking a list and joining its elements into a string: ### >>> mystr = string.join(numbers, "") >>> len(mystr) 488890 ### It's better at it because it expects not to do the "write/erase/write" sort of thing: it really does try to writing things out all at once. And it does it pretty quickly. Your code: > tab = "\n" > for x in result: > tab = tab + "" > tab = tab + string.join(map(f1,x),"")+"\n" > tab = tab + "
" can use a similar trick if you use a list to hold all the temporary string fragments, and this is probably one of the best ways to speed it up. Alternatively, if you like working with files, you can use a StringIO() object to temporarily hold things while you're concatenating: ### >>> import StringIO >>> stringout = StringIO.StringIO() >>> for element in numbers: ... stringout.write(element) ... >>> len(stringout.getvalue()) 488890 ### Subjectively, using StringIO does feel a little slower than using the string.join()ing, but it also works effectively. Hope this helps! From alan.gauld@bt.com Tue Oct 30 11:28:03 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 30 Oct 2001 11:28:03 -0000 Subject: [Tutor] proper return style Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C03D@mbtlipnt02.btlabs.bt.co.uk> > What's the rule about using a explicit return command in > functions? return returns values - which may be None... > works the same as: > > def printSquare(number): > print number**2 > > What's preferred? Personally I prefer the second case shown above. If there's nothing to return don't use return... But thats just my personal preference. Alan g. From aschmidt@nv.cc.va.us Tue Oct 30 14:39:55 2001 From: aschmidt@nv.cc.va.us (Schmidt, Allen J.) Date: Tue, 30 Oct 2001 09:39:55 -0500 Subject: [Tutor] Reading matching text files in a folder Message-ID: <5CDFEBB60E7FD311B9E30000F6D6090608CB8DB1@novamail2.nv.cc.va.us> I've been lurking for a while but now need some help... I have a program that reads a hard-coded filename and path like "F:\\import\\20011030-Tue.txt" It works and breaks each line up into parts, strips out apostrophes and inserts the fields into a MySQL database table. What I need to be able to do: Look into the above folder (F:\\import\\) and see if there are any *.txt files in it. If so, pass it by name into my loop that breaks it up and does the DB insert. I also need access to the date (20011030) and the day (Tue) to use as fields in the insert. Then when done, rename the file by adding some prefix and suffix so it is not processed again the next day. AND...if there is more than one, loop through each of them in turn and perform the above needed actions. Have not worked with files much and need some guidance. Links to examples also appreciated. Thanks Allen From lkvam@venix.com Tue Oct 30 14:55:58 2001 From: lkvam@venix.com (Lloyd Kvam) Date: Tue, 30 Oct 2001 09:55:58 -0500 Subject: [Tutor] Reading matching text files in a folder References: <5CDFEBB60E7FD311B9E30000F6D6090608CB8DB1@novamail2.nv.cc.va.us> Message-ID: <3BDEBF7E.D4397257@venix.com> Some code snippets to help: >>> flist = os.popen("dir *.py /B").readlines() >>> flist ['class_test.py\012', 'fib.py\012', 'fnx_counts.py\012', 'ia_test.py\012', 'lloyd_util.py\012', 'localhost_8000.py\012', 'parkAP.py\012', 'parkCGI.py\012', 'parkCOM.py\012', 'park_test.py\012', 'pos.py\012', 'resv.py\012', 'sqrt_sum.py\012', 'testdict.py\012', 'testresv.py\012', 'three_n_plus_one.py\012', 'ui_dict.py\012', 'util.py\012'] >>> import DateTime >>> xdate = DateTime.Date(2001,3,15) # the ides of March, 2001 >>> xdate.day 15 >>> xdate.day_of_week 3 Programming Python (Lutz) devotes chapter 2 to covering System Tools: reading directories and processing files. DateTime is from mxDateTime a very complet package of date and time handling tools. "Schmidt, Allen J." wrote: > > I've been lurking for a while but now need some help... > > I have a program that reads a hard-coded filename and path like > "F:\\import\\20011030-Tue.txt" > > It works and breaks each line up into parts, strips out apostrophes and > inserts the fields into a MySQL database table. > > What I need to be able to do: > Look into the above folder (F:\\import\\) and see if there are any *.txt > files in it. > If so, pass it by name into my loop that breaks it up and does the DB > insert. > I also need access to the date (20011030) and the day (Tue) to use as fields > in the insert. > Then when done, rename the file by adding some prefix and suffix so it is > not processed again the next day. > > AND...if there is more than one, loop through each of them in turn and > perform the above needed actions. > > Have not worked with files much and need some guidance. Links to examples > also appreciated. > > Thanks > > Allen > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From toodles@yifan.net Tue Oct 30 15:07:14 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Tue, 30 Oct 2001 23:07:14 +0800 Subject: [Tutor] Reading matching text files in a folder References: <5CDFEBB60E7FD311B9E30000F6D6090608CB8DB1@novamail2.nv.cc.va.us> Message-ID: <000701c16154$8ffc0550$0300a8c0@sun> Hi Allen > I've been lurking for a while but now need some help... Isn't lurking fun? :) > > I have a program that reads a hard-coded filename and path like > "F:\\import\\20011030-Tue.txt" > > It works and breaks each line up into parts, strips out apostrophes and > inserts the fields into a MySQL database table. > > What I need to be able to do: > Look into the above folder (F:\\import\\) and see if there are any *.txt > files in it. > If so, pass it by name into my loop that breaks it up and does the DB > insert. > I also need access to the date (20011030) and the day (Tue) to use as fields > in the insert. > Then when done, rename the file by adding some prefix and suffix so it is > not processed again the next day. > > AND...if there is more than one, loop through each of them in turn and > perform the above needed actions. Okay I'll make a couple of assumptions firstly: 1) All dates will always be the characters from the beginning to the first hyphen. 2) All days will be the characters proceding the first hyphen and preceding the first full-stop. #################### Following code not completely tested... import os def do_stuff_to_file(filename): #do stuff to file here... filenames=os.listdir("F:\\import\\") #Okay, firstly we need to get a list of files in the directory filenames=[filename.lower() for filename in filenames if filename[-4:].lower()==".txt"] #Replace filenames with the filenames whose last 4 characters are ".txt". Use list comprehensions! Yay! for filename in filenames: do_stuff_to_file(filename) #################### > Have not worked with files much and need some guidance. Links to examples > also appreciated. > > Thanks > > Allen No worries, Andrew > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From scarblac@pino.selwerd.nl Tue Oct 30 15:04:20 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Tue, 30 Oct 2001 16:04:20 +0100 Subject: [Tutor] Reading matching text files in a folder In-Reply-To: <5CDFEBB60E7FD311B9E30000F6D6090608CB8DB1@novamail2.nv.cc.va.us>; from aschmidt@nv.cc.va.us on Tue, Oct 30, 2001 at 09:39:55AM -0500 References: <5CDFEBB60E7FD311B9E30000F6D6090608CB8DB1@novamail2.nv.cc.va.us> Message-ID: <20011030160420.A28911@pino.selwerd.nl> On 0, "Schmidt, Allen J." wrote: > I've been lurking for a while but now need some help... > > I have a program that reads a hard-coded filename and path like > "F:\\import\\20011030-Tue.txt" > > It works and breaks each line up into parts, strips out apostrophes and > inserts the fields into a MySQL database table. > > What I need to be able to do: > Look into the above folder (F:\\import\\) and see if there are any *.txt > files in it. import os files = os.listdir("F:\\import\\*.txt") Gives a list of files. > If so, pass it by name into my loop that breaks it up and does the DB > insert. for file in files: pass_into_his_loop(file) > I also need access to the date (20011030) and the day (Tue) to use as fields > in the insert. filename = os.path.basename(file) dash = filename.index('-') dot = filename.index('.') date = filename[:dash] day = filename[dash+1:dot] That's a very brute force and hard coded way, but if your files always look like that it'll work ok. If you have an old Python you can use string.index() or string.find() to find the index. > Then when done, rename the file by adding some prefix and suffix so it is > not processed again the next day. Use os.rename() to rename files, eg os.rename(filename, filename+".DONE") > AND...if there is more than one, loop through each of them in turn and > perform the above needed actions. That's what the loop above did. > > Have not worked with files much and need some guidance. Links to examples > also appreciated. Hope this helps. The os, os.path and string modules should have everything you need. -- Remco Gerlich From toodles@yifan.net Tue Oct 30 15:18:05 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Tue, 30 Oct 2001 23:18:05 +0800 Subject: [Tutor] Reading matching text files in a folder Message-ID: <000e01c16156$147f66e0$0300a8c0@sun> *Slaps himself in the face* I forgot to include the date part after all... ----- Original Message ----- From: "Andrew Wilkins" To: "Schmidt, Allen J." ; Sent: Tuesday, October 30, 2001 11:07 PM Subject: Re: [Tutor] Reading matching text files in a folder > Hi Allen > > > > I've been lurking for a while but now need some help... > Isn't lurking fun? :) > > > > > I have a program that reads a hard-coded filename and path like > > "F:\\import\\20011030-Tue.txt" > > > > It works and breaks each line up into parts, strips out apostrophes and > > inserts the fields into a MySQL database table. > > > > What I need to be able to do: > > Look into the above folder (F:\\import\\) and see if there are any *.txt > > files in it. > > If so, pass it by name into my loop that breaks it up and does the DB > > insert. > > I also need access to the date (20011030) and the day (Tue) to use as > fields > > in the insert. > > Then when done, rename the file by adding some prefix and suffix so it is > > not processed again the next day. > > > > AND...if there is more than one, loop through each of them in turn and > > perform the above needed actions. > > Okay I'll make a couple of assumptions firstly: > 1) All dates will always be the characters from the beginning to the first > hyphen. > 2) All days will be the characters proceding the first hyphen and preceding > the first full-stop. > #################### Following code not completely tested... import os def do_stuff_to_file(filename): #do stuff to file here... filenames=os.listdir("F:\\import\\") #Okay, firstly we need to get a list of files in the directory filenames=[filename.lower() for filename in filenames if (filename[-4:].lower()==".txt" and filename[0]!="-")] #Replace filenames with the filenames whose last 4 characters are ".txt" and first 1 isn't "-". Use list comprehensions! Yay! insert_info={} for filename in filenames: insert_info[filename]=(filename[:filename.index('-')],filename[filename.inde x('-')+1:filename.index('.')) #get the info for using in the inserts...i don't know exactly what you want to do with them, so i'll leave that up to you. os.rename("F:\\import\\"+filename,"F:\\import\\-"+filename) #prefix with a hyphen for filename in filenames: do_stuff_to_file(filename) #################### Okay sorry about the screw-up. :( > > > Have not worked with files much and need some guidance. Links to examples > > also appreciated. > > > > Thanks > > > > Allen > > No worries, > Andrew > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From toodles@yifan.net Tue Oct 30 15:18:05 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Tue, 30 Oct 2001 23:18:05 +0800 Subject: [Tutor] Reading matching text files in a folder Message-ID: <000e01c16156$147f66e0$0300a8c0@sun> *Slaps himself in the face* I forgot to include the date part after all... ----- Original Message ----- From: "Andrew Wilkins" To: "Schmidt, Allen J." ; Sent: Tuesday, October 30, 2001 11:07 PM Subject: Re: [Tutor] Reading matching text files in a folder > Hi Allen > > > > I've been lurking for a while but now need some help... > Isn't lurking fun? :) > > > > > I have a program that reads a hard-coded filename and path like > > "F:\\import\\20011030-Tue.txt" > > > > It works and breaks each line up into parts, strips out apostrophes and > > inserts the fields into a MySQL database table. > > > > What I need to be able to do: > > Look into the above folder (F:\\import\\) and see if there are any *.txt > > files in it. > > If so, pass it by name into my loop that breaks it up and does the DB > > insert. > > I also need access to the date (20011030) and the day (Tue) to use as > fields > > in the insert. > > Then when done, rename the file by adding some prefix and suffix so it is > > not processed again the next day. > > > > AND...if there is more than one, loop through each of them in turn and > > perform the above needed actions. > > Okay I'll make a couple of assumptions firstly: > 1) All dates will always be the characters from the beginning to the first > hyphen. > 2) All days will be the characters proceding the first hyphen and preceding > the first full-stop. > #################### Following code not completely tested... import os def do_stuff_to_file(filename): #do stuff to file here... filenames=os.listdir("F:\\import\\") #Okay, firstly we need to get a list of files in the directory filenames=[filename.lower() for filename in filenames if (filename[-4:].lower()==".txt" and filename[0]!="-")] #Replace filenames with the filenames whose last 4 characters are ".txt" and first 1 isn't "-". Use list comprehensions! Yay! insert_info={} for filename in filenames: insert_info[filename]=(filename[:filename.index('-')],filename[filename.inde x('-')+1:filename.index('.')) #get the info for using in the inserts...i don't know exactly what you want to do with them, so i'll leave that up to you. os.rename("F:\\import\\"+filename,"F:\\import\\-"+filename) #prefix with a hyphen for filename in filenames: do_stuff_to_file(filename) #################### Okay sorry about the screw-up. :( > > > Have not worked with files much and need some guidance. Links to examples > > also appreciated. > > > > Thanks > > > > Allen > > No worries, > Andrew > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From alan.gauld@bt.com Tue Oct 30 15:34:14 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 30 Oct 2001 15:34:14 -0000 Subject: [Tutor] [Q] Python, Jython, and drawing application Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C041@mbtlipnt02.btlabs.bt.co.uk> ------_=_NextPart_001_01C16158.547DA020 Content-type: text/plain; charset="ISO-8859-1" Hi, I'm new to Python programming and I have a question. If I make a Jython application, can the Jython application use the Java application? I have a Java application and I want to switch my programming language to Python, but I don't want to dump my Java application. If it's possible, how can I do it? Probably better joining the jython mailing list for these but here's the little I understand(or think I do...) Yes you can access your existing Java code, at least at the class level. You can create and use Java objects pretty much transpoarantly - thats whjat happens when you use the AWT for example. Any good tutorials? How about performance? My informal testing suggests Jython is about half the speed of native Java. Or about a quarter the speed of CPython. I have read the Python tutorial and I felt like Python is most focusing a server programming. Its a general purpose language like C++ or Perl etc. (Relatively little documentation and tutorial on GUI exists.) If you mean books then I agree, there are several online resources tho', especially for Tkinter. How difficult would it be to develop a petri net drawing or a UML drawing application? Check out DIA - it is a Visio like drawing package written in Python. At least I think it is - I might be confusing it with something else - Sketch maybe? There definitely is a drawing package out there written in Python. So yes you could build a UML tool. You could also look at the now obsolescent Grail web browser, also written in Python. Is there any example code for these kinds of python application? Both of the above are opensource so you can download the code. Alan g ------_=_NextPart_001_01C16158.547DA020 Content-type: text/html; charset="ISO-8859-1"
Hi, I'm new to Python programming and I have a question.
If I make a Jython application, can the Jython application use the Java application?
I have a Java application and I want to switch my programming language to Python, but I don't want to dump my Java application. If it's possible, how can I do it?  
Probably better joining the jython mailing list for
these but here's the little I understand(or think I do...)
 
Yes you can access your existing Java code, at least
at the class level. You can create and use Java objects
pretty much transpoarantly - thats whjat happens when
you use the AWT for example.
 Any good tutorials? How about performance? 
My informal testing suggests Jython is about half the
speed of native Java. Or about a quarter the speed of
CPython.
 
I have read the Python tutorial and I felt like Python is most focusing a server programming.  
 
Its a general purpose language like C++ or Perl etc.
 (Relatively little documentation and tutorial on GUI exists.)  
 
If you mean books then I agree, there are several
online resources tho', especially for Tkinter.
 How difficult would it be to develop a petri net drawing or a UML drawing application?  
 
Check out DIA - it is a Visio like drawing package
written in Python. At least I think it is - I might
be confusing it with something else - Sketch maybe?
 
There definitely is a drawing package out there
written in Python. So yes you could build a UML
tool.
 
You could also look at the now obsolescent Grail
web browser, also written in Python.
Is there any example code for these kinds of python application? 
Both of the above are opensource so you can
download the code.
 
Alan g
------_=_NextPart_001_01C16158.547DA020-- From alan.gauld@bt.com Tue Oct 30 15:44:05 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 30 Oct 2001 15:44:05 -0000 Subject: [Tutor] Can someone help me to improve this segment? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C042@mbtlipnt02.btlabs.bt.co.uk> > ************main program piece*********** > tab = "\n %s \n
" s = "" > for x in result: > s = s + "" + string.join(map(f1,x),"")+"\n" > tab = tab % s > Can anyone improve this code segment? Thanks alot Avoids copying the original tab each time. Alan g From Charlie@begeistert.org Tue Oct 30 15:58:26 2001 From: Charlie@begeistert.org (Charlie Clark) Date: Tue, 30 Oct 2001 16:58:26 +0100 Subject: [Tutor] Re: explicit return functions In-Reply-To: Message-ID: <1004457507_PM_BeOS.Charlie@begeistert.org> >> What's the rule about using a explicit return command in >> functions? > >return returns values - which may be None... > >> works the same as: >> >> def printSquare(number): >> print number**2 >> >> What's preferred? > >Personally I prefer the second case shown above. If >there's nothing to return don't use return... > I think, but I may well be wrong, that the difference is more than mere preference. Using "return" and "print" in the Pyhton interpreter will always seem to do the same thing but that isn't the case inside programs. If you want to *see* the result of a function you should just print it. If you want to *use* the result of a function, return it. def PrintSquare(x): print x**2 def ReturnSquare(x): return x**2 now try this: PrintSquare(3) >>> 9 ReturnSquare(3) >>> 9 but try result = PrintSquare(3) >>> 9 print result # prints nothing as result has not been assigned a value result = ReturnSquare(3) >>> print result 9 Returning the value allows to do something with it. Charlie From lkvam@venix.com Tue Oct 30 22:22:02 2001 From: lkvam@venix.com (Lloyd Kvam) Date: Tue, 30 Oct 2001 17:22:02 -0500 Subject: [Tutor] Can someone help me to improve this segment? References: <20011030052716.18291.qmail@web14707.mail.yahoo.com> Message-ID: <3BDF280A.D78A5EDC@venix.com> This suggestion may not fit in with the rest of what you are doing, but HTMLgen is reasonably quick and easy for creating HTML output. A table is built from nested lists. Since the HTML text is built in one swoop, not by modifying an existing string, it seems quick enough. It is simply necessary to build the lists of data. Here is my block of code. The table being generated runs 6 to 12 pages depending upon the selected data. def toHTML( self, rptname="Cumulative Findings Report", rptinfo="Test Version"): doc = HTMLgen.SimpleDocument() h = HTMLgen.Heading( 1, rptname) doc.append(h) table = HTMLgen.Table( rptinfo) table.heading = [' '] + map( lambda a: a.label, self.cols) table.body = [] # r is the first row and contains column totals r = [' '] # first column generally contains row labels for col in self.cols: r.append(get0( col.counts)) table.body.append(r) for block in self.blocks: table.body.append( [block.title] + [' ']*len(self.cols)) for row in block.rows: drow = block.tagRows.get(row.subcol_name, None) table.body.append( [row.label] + row.pct0( self.cols, drow)) doc.append( table) doc.write My only serious glitch in doing this was insuring that each row contains the same number of columns. In terms of your snippet of code: ... table = HTMLgen.Table('Table Title') table.body = result doc.append(table) The HTMLgen code is available at: http://starship.python.net/crew/friedrich/HTMLgen/html/main.html You can see for yourself how the HTML tags get produced. Titu Kim wrote: > > Hi, > I am little obssessed with my own coded after i > found out it is slow. I am trying to construct a html > table string from a result that i obtain from > database.My code segment look like this: assume result > holds 2D list. > ******* method******************************** > def f1(item): > return ""+str(item)+"" > ***************************************** > ************main program piece*********** > tab = "\n" > for x in result: > tab = tab + "" > tab = tab + string.join(map(f1,x),"")+"\n" > tab = tab + "
" > ********************************************** > Can anyone improve this code segment? Thanks alot > > Regards, > > Kim Titu > > > __________________________________________________ > Do You Yahoo!? > Make a great connection at Yahoo! Personals. > http://personals.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From kromag@nsacom.net Wed Oct 31 00:57:50 2001 From: kromag@nsacom.net (kromag@nsacom.net) Date: Tue, 30 Oct 2001 16:57:50 -0800 (PST) Subject: [Tutor] Waiting for input. Message-ID: <200110310057.f9V0vor31129@pop.nsacom.net> (I just found the range() function, so this will change soon! :-) It kinda works like I want it to at this point....) I would like to have the following function pause between loops: ------------------the following function------------------ def do_r(self,_): saved=open('save','r') messagebase=cPickle.load(saved) saved.close() post=messagebase.keys() ticker=1 count=len(messagebase)+1 while ticker < count: post=messagebase[ticker] print 'nn Posted by: '+post[0]+' '+time.ctime(post[1])+'n'+post[2] ticker=ticker+1 -----------------biting off more than I can chew..--------- I keep scoping the Basic Statements chapter in "Learning Python" and have found nothing that seems to fit. Where do I need to look? Thanks folks! From lkvam@venix.com Tue Oct 30 23:04:15 2001 From: lkvam@venix.com (Lloyd Kvam) Date: Tue, 30 Oct 2001 18:04:15 -0500 Subject: [Tutor] Waiting for input. References: <200110310057.f9V0vor31129@pop.nsacom.net> Message-ID: <3BDF31EF.205AB8EF@venix.com> Do you want an automatic pause? import time time.sleep(5) # sleep 5 seconds http://www.python.org/doc/current/lib/module-time.html#l2h-1298 http://www.python.org/doc/current/lib/console-objects.html#l2h-567 Here you would issue a prompt and wait for user input. reply = raw_input("Press enter when you are ready to continue!") kromag@nsacom.net wrote: > > (I just found the range() function, so this will change soon! :-) It kinda > works like I want it to at this point....) > > I would like to have the following function pause between loops: > > ------------------the following function------------------ > def do_r(self,_): > saved=open('save','r') > messagebase=cPickle.load(saved) > saved.close() > post=messagebase.keys() > ticker=1 > count=len(messagebase)+1 > while ticker < count: > post=messagebase[ticker] > print 'nn Posted by: '+post[0]+' > '+time.ctime(post[1])+'n'+post[2] > ticker=ticker+1 > > -----------------biting off more than I can chew..--------- > > I keep scoping the Basic Statements chapter in "Learning Python" and have > found nothing that seems to fit. Where do I need to look? > > Thanks folks! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From dyoo@hkn.eecs.berkeley.edu Tue Oct 30 23:06:08 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 30 Oct 2001 15:06:08 -0800 (PST) Subject: [Tutor] Waiting for input. In-Reply-To: <200110310057.f9V0vor31129@pop.nsacom.net> Message-ID: rOn Tue, 30 Oct 2001 kromag@nsacom.net wrote: > (I just found the range() function, so this will change soon! :-) It kinda > works like I want it to at this point....) > > I would like to have the following function pause between loops: By "pause", do you want your program to wait until you've pressed a key, or do you mean something like "wait for a few seconds"? If it's the "Press any key to continue" kind of pause, you might want to try raw_input(): ### >>> raw_input("Press Enter to continue: ") Press Enter to continue: '' ### The idea is that we use raw_input() just to force the program to wait for the user to interact with our program. If it's the "wait for a few seconds" kind of pause, you may want to look at time.sleep(): ### >>> print time.sleep.__doc__ sleep(seconds) Delay execution for a given number of seconds. The argument may be a floating point number for subsecond precision. ### Hope this helps! From deirdre@deirdre.net Wed Oct 31 04:45:18 2001 From: deirdre@deirdre.net (Deirdre Saoirse Moen) Date: Tue, 30 Oct 2001 20:45:18 -0800 Subject: [Tutor] [OT] Bay PIGgies hijacked? In-Reply-To: <20011025110234.A29346@harmony.cs.rit.edu> References: <20011025110234.A29346@harmony.cs.rit.edu> Message-ID: >I'm sending this to the list because IIRC there are some people on >this list that are part of the Bay PIGgies group. I sent a private >message to someone earlier, but they're not part of the baypiggies. > >---- > >I just tried to follow a link to an intro on using libglade with >python on www.baypiggies.org, but ended up at a porn site >8^p. Did >someone screw up the DNS records? Is there a way I can get to the >site (is it a static IP that you can share)? > >BTW, the link was on an old GNOME news page found by Google. The news >item is dated "Nov. 21" so it must be at least almost a year old. As Danny said, I didn't renew the domain, it lapsed, and someone else bought it. I had to make some hard choices about what domains to keep going and which to let lapse unfortunately. As Danny said, it is (now) up at http://deirdre.org/baypiggies/ but I haven't fixed any of the links that may be broken. I'd intended on doing it last week but was ill and trying to get something done. -- _Deirdre * http://deirdre.net "I live in comfort knowing that my early works were not printed on acid-free paper." -- Lawrence Block From dsh8290@rit.edu Wed Oct 31 16:18:59 2001 From: dsh8290@rit.edu (dman) Date: Wed, 31 Oct 2001 11:18:59 -0500 Subject: [Tutor] [OT] Bay PIGgies hijacked? In-Reply-To: ; from deirdre@deirdre.net on Tue, Oct 30, 2001 at 08:45:18PM -0800 References: <20011025110234.A29346@harmony.cs.rit.edu> Message-ID: <20011031111859.A14582@harmony.cs.rit.edu> On Tue, Oct 30, 2001 at 08:45:18PM -0800, Deirdre Saoirse Moen wrote: | >I'm sending this to the list because IIRC there are some people on | >this list that are part of the Bay PIGgies group. I sent a private | >message to someone earlier, but they're not part of the baypiggies. | > | >---- | > | >I just tried to follow a link to an intro on using libglade with | >python on www.baypiggies.org, but ended up at a porn site >8^p. Did | >someone screw up the DNS records? Is there a way I can get to the | >site (is it a static IP that you can share)? | > | >BTW, the link was on an old GNOME news page found by Google. The news | >item is dated "Nov. 21" so it must be at least almost a year old. | | As Danny said, I didn't renew the domain, it lapsed, and someone else | bought it. | | I had to make some hard choices about what domains to keep going and | which to let lapse unfortunately. Yeah, that happens. I wasn't aware of the change until now. | As Danny said, it is (now) up at http://deirdre.org/baypiggies/ but I Cool, now I see something there :-). | haven't fixed any of the links that may be broken. I'd intended on | doing it last week but was ill and trying to get something done. If the URLs use relative paths, then there should be no problems. I tried the one link that goes to the glade intro, and it works. -D From david.jay.jackson@wcox.com Wed Oct 31 17:04:34 2001 From: david.jay.jackson@wcox.com (Jackson) Date: Wed, 31 Oct 2001 10:04:34 -0700 Subject: [Tutor] Using re/search with dictionaries Message-ID: <200110311004.AA435487034@wcox.com> Greetings -- How do I search dict keys? and return the records that go along with them? It seems as if it should be something along this line: # we're looking for keys/records with blue* in them. m=rd.search("\w[blue]+",d.keys()) if m: print repr(m.group(0)) and the output should be: [blue-001"]=["blueberry pie"] ["blue-002"]=["blueberry cobbler"] ["blue-003"]=["blueberry muffins"] ... .... Thanks for you time David Jackson --------------- create dict script ---------------------- #!/usr/bin/python import re d = {} d["blue-001"]=["blueberry pie"] d["blue-002"]=["blueberry cobbler"] d["blue-003"]=["blueberry muffins"] d["cherry-001"]=["cherry pie"] d["cherry-002"]=["wild cherry icecream"] d["blueberry"]=["muffins"] d["bluebird"]=["feathered friend"] d["red red robin"]=["goes bob bob bobing along"] From urnerk@qwest.net Wed Oct 31 17:24:56 2001 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 31 Oct 2001 09:24:56 -0800 Subject: [Tutor] Using re/search with dictionaries In-Reply-To: <200110311004.AA435487034@wcox.com> Message-ID: <4.2.0.58.20011031091951.00c66ca0@pop3.norton.antivirus> Regular expressions search strings, not lists, so you can't use d.keys() as an arg to re.search() -- would have to do some conversion to/from to make this approach work. But regular expressions might be overkill if you're just wanting to find keys with embedded strings, nothing much fancier. Simpler string functions will do that job. Defining dictionary d as per your setup script, the function below lists all key/value pairs where the passed pattern (e.g. "blue") is found in the key: >>> def getmatches(pattern, thedict): keys = [i for i in thedict.keys() if i.find(pattern)>=0] for k in keys: print "%s = %s" % (k,thedict[k]) >>> getmatches("blue",d) blue-003 = ['blueberry muffins'] blue-002 = ['blueberry cobbler'] blue-001 = ['blueberry pie'] blueberry = ['muffins'] bluebird = ['feathered friend'] You could modify the above to work with regular expressions, but it'd search each key, one at a time. Again, if simple string functions will do the job, they're faster. Kirby At 10:04 AM 10/31/2001 -0700, Jackson wrote: >Greetings -- >How do I search dict keys? and return the records that go along with them? >It seems as if it should be something along this line: > ># we're looking for keys/records with blue* in them. >m=rd.search("\w[blue]+",d.keys()) >if m: print repr(m.group(0)) > and the output should be: > >[blue-001"]=["blueberry pie"] >["blue-002"]=["blueberry cobbler"] >["blue-003"]=["blueberry muffins"] >... >.... > > >Thanks for you time >David Jackson From jeff@ccvcorp.com Wed Oct 31 17:41:52 2001 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed, 31 Oct 2001 09:41:52 -0800 Subject: [Tutor] Waiting for input. References: Message-ID: <3BE037DF.2D7BB688@ccvcorp.com> > From: > > I would like to have the following function pause between loops: > Several people have already answered your question about pausing, but there's a few other odd things in your function that I'd like to point out.... > ------------------the following function------------------ > def do_r(self,_): You're passing two variables here, the implicit self (so this is really a method, rather than an unbound function?) and '_', which you never use. Any reason to include it at all? > saved=open('save','r') > messagebase=cPickle.load(saved) > saved.close() > post=messagebase.keys() Here you assign a list of keys to post .... > > ticker=1 > count=len(messagebase)+1 > while ticker < count: > post=messagebase[ticker] then here, you totally overwrite the list of keys, with a single value.... > > print 'nn Posted by: '+post[0]+' > '+time.ctime(post[1])+'n'+post[2] .... which looks to be another list (or tuple?). So why the original assignment of post=messagebase.keys() ? You never use that value before replacing it with post=messagebase[ticker]. Not only that, but your explicit while-loop and counter variable, would be better done with a for-loop which handles counters and indexing implicitly. And as a minor additional note, you add a bunch of strings together for your print statement--string concatenation like this is very inefficient in Python, you're much better using formatted substitution instead. So, a quick rewrite of your function (guessing a bit as to the contents of your pickle...): def do_r(self): saved = open('save','r') messagebase = cPickle.load(saved) saved.close() for msg in messagebase: print 'nn Posted by: %s %s n %s' % (msg[0], time.ctime(msg[1]), msg[2]) time.sleep(2) #presuming that this is how you wanted to pause.... Obviously, if your pickle is something other than a list of lists (or list of tuples), then this will need modified to handle whatever data is actually in the pickle. You're also not doing anything with the contents of the pickle, other than printing them--it'd be easy to add whatever processing you want into the for-loop. Hope that this provides some food for thought... :) Jeff Shannon Technician/Programmer Credit International From bob_lunney@yahoo.com Wed Oct 31 18:13:30 2001 From: bob_lunney@yahoo.com (Bob Lunney) Date: Wed, 31 Oct 2001 10:13:30 -0800 (PST) Subject: [Tutor] Argument values in C extension functions Message-ID: <20011031181330.72872.qmail@web9704.mail.yahoo.com> I've inherited a (very cool) piece of Python code that uses a C extension library. In the library code are checks to determine if the extension function is receiving anything in the PyObject* args tuple. It checks this by seeing if args != NULL. If so, it bales out. This particular function requires keyword arguments, and the PyMethodDef struct is set up to use METH_KEYWORDS. My question is: will args necessarily be NULL (in Python 2.1) when using keyword argument passing. This worked in Python 1.5.1, but no longer works in Python 2.1. If the extension function calling protocol has changed between the two Python versions will someone please give me a synopsis of the changes or point me to the appropriate resource material? Thanks in advance, Bob Lunney __________________________________________________ Do You Yahoo!? Make a great connection at Yahoo! Personals. http://personals.yahoo.com From virketis@fas.harvard.edu Wed Oct 31 20:09:23 2001 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Wed, 31 Oct 2001 15:09:23 -0500 (EST) Subject: [Tutor] problem installing MySQLdb Message-ID: Hi, here is a message I got from my ISP when I asked them to install the MySQLdb module: ------------------------ error message ------------------------- Hi, I tried installing the MySQL python module and it gives me this error. [root@host14 MySQL-python-0.9.1]# python setup.py build Traceback (innermost last): File "setup.py", line 6, in ? from distutils.core import setup ImportError: No module named distutils.core Where can I get the distutils.core module? After I install that I'll try to install the python MySQL module again. Thanks. --------------------------- end error message ------------------- I am not a big expert on the internals of Python, but distutils.core is not a typical name for a "module", is it? What could be the problem here? My ISP is running Python 1.5.1 on (probably) Linux. They use Apache. Thank you! Pijus From ylee12@uiuc.edu Wed Oct 31 21:12:16 2001 From: ylee12@uiuc.edu (Young-Jin Lee) Date: Wed, 31 Oct 2001 15:12:16 -0600 Subject: [Tutor] [Q] Tkinter Message-ID: <009a01c16250$b7eea2a0$95757e82@visit2> This is a multi-part message in MIME format. ------=_NextPart_000_0097_01C1621E.6D0F6170 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, all. I have a question using Tkiner. Here is the sample code I used.=20 from Tkinter import * class App: def __init__(self, master): frame =3D Frame(master) frame.pack() self.button =3D Button(frame, text=3D"QUIT", fg=3D"red", = command=3Dframe.quit) self.button.pack(side=3DLEFT) self.hi_there =3D Button(frame, text=3D"Hello", = command=3Dself.say_hi) self.hi_there.pack(side=3DLEFT) def say_hi(self): print "hi there, everyone!" root =3D Tk() app =3D App(root) root.mainloop() How can I make this test application to quit instead of Python shell = itself? When I click the quit button, the IDLE itself quits. This is not = what I wanted. I want to close only this application. How can I do this? Thanks. ------=_NextPart_000_0097_01C1621E.6D0F6170 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi, all.
I have a question using Tkiner. Here is = the sample=20 code I used.
 
from Tkinter import *

class=20 App:

    def __init__(self,=20 master):

        frame =3D=20 Frame(master)
       =20 frame.pack()

        = self.button =3D=20 Button(frame, text=3D"QUIT", fg=3D"red",=20 command=3Dframe.quit)
       =20 self.button.pack(side=3DLEFT)

      =  =20 self.hi_there =3D Button(frame, text=3D"Hello",=20 command=3Dself.say_hi)
       =20 self.hi_there.pack(side=3DLEFT)

    def=20 say_hi(self):
        print "hi = there,=20 everyone!"

root =3D Tk()

app =3D=20 App(root)

root.mainloop()
How can I make this test application to = quit=20 instead of Python shell itself? When I click the quit button, the IDLE = itself=20 quits. This is not what I wanted. I want to close only this application. = How can=20 I do this?
Thanks.
------=_NextPart_000_0097_01C1621E.6D0F6170-- From james2dope@yahoo.com Wed Oct 31 20:41:28 2001 From: james2dope@yahoo.com (james middendorff) Date: Wed, 31 Oct 2001 12:41:28 -0800 (PST) Subject: [Tutor] help Message-ID: <20011031204128.46041.qmail@web13903.mail.yahoo.com> --0-1770206085-1004560888=:42694 Content-Type: text/plain; charset=us-ascii hello, could someone please tell me how to display a text file, and then be able to type more information into that file? thanks "I would kill everyone in this room for a drop of sweet beer." ----Homer Simpson---- --------------------------------- Do You Yahoo!? Make a great connection at Yahoo! Personals. --0-1770206085-1004560888=:42694 Content-Type: text/html; charset=us-ascii

hello,

could someone please tell me how to display a text file, and then be able to type more information into that file?

thanks



"I would kill everyone in this room
for a drop of sweet beer."
----Homer Simpson----



Do You Yahoo!?
Make a great connection at Yahoo! Personals. --0-1770206085-1004560888=:42694-- From kalle@gnupung.net Wed Oct 31 21:36:02 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Wed, 31 Oct 2001 22:36:02 +0100 Subject: [Tutor] problem installing MySQLdb In-Reply-To: References: Message-ID: <20011031223602.B1935@sandra.lysator.liu.se> [Pijus Virketis] > Hi, > > here is a message I got from my ISP when I asked them to install the > MySQLdb module: > > ------------------------ error message ------------------------- [...] > ImportError: No module named distutils.core [...] > --------------------------- end error message ------------------- > > I am not a big expert on the internals of Python, but distutils.core is > not a typical name for a "module", is it? What could be the problem here? > My ISP is running Python 1.5.1 on (probably) Linux. They use Apache. distutils.core is a module in tha package distutils. Distutils is standard with Python 1.6 and later and is a framework for installing modules. It can be downloaded from http://www.python.org/sigs/distutils-sig/download.html but I don't know if it works with 1.5.1. It's worth a try, though. Peace, Kalle -- [ Thought control, brought to you by the WIPO! ] [ http://anti-dmca.org/ http://eurorights.org/ ] From dyoo@hkn.eecs.berkeley.edu Wed Oct 31 21:37:48 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 31 Oct 2001 13:37:48 -0800 (PST) Subject: [Tutor] problem installing MySQLdb In-Reply-To: Message-ID: On Wed, 31 Oct 2001, Pijus Virketis wrote: > here is a message I got from my ISP when I asked them to install the > MySQLdb module: > > ------------------------ error message ------------------------- > Hi, > > I tried installing the MySQL python module and it gives me this error. > > [root@host14 MySQL-python-0.9.1]# python setup.py build > Traceback (innermost last): > File "setup.py", line 6, in ? > from distutils.core import setup > ImportError: No module named distutils.core Installing new Python modules requires the "Distutils" module installation system. Distutils is a system that makes installing Python modules relatively easy, so that's why MySQLdb uses it. Distutils been part of Python since 1.6, but since your ISP is running Python 1.51, you'll want to ask them to install the Distutils as well. You can find the Distutils system here: http://python.org/sigs/distutils-sig/download.html Good luck! From ak@silmarill.org Wed Oct 31 21:41:27 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Wed, 31 Oct 2001 16:41:27 -0500 Subject: [Tutor] help In-Reply-To: <20011031204128.46041.qmail@web13903.mail.yahoo.com> References: <20011031204128.46041.qmail@web13903.mail.yahoo.com> Message-ID: <20011031164127.A11972@sill.silmarill.org> On Wed, Oct 31, 2001 at 12:41:28PM -0800, james middendorff wrote: > > hello, > > could someone please tell me how to display a text file, and then be able to type more information into that file? > > thanks Not exactly sure what you mean by that, but this would work: import os os.system("vim file") > > > "I would kill everyone in this room > for a drop of sweet beer." > ----Homer Simpson---- > > > --------------------------------- > Do You Yahoo!? > Make a great connection at Yahoo! Personals. -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From virketis@fas.harvard.edu Wed Oct 31 22:40:48 2001 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Wed, 31 Oct 2001 17:40:48 -0500 Subject: [Tutor] MySQLdb saga continues :( Message-ID: <200110312239.f9VMdpZ08488@smtp4.fas.harvard.edu> Hi again, well, my helpfull ISP admin sent me this message: --------------------- error message ---------------------- OK, I downloaded Disutils and followed the install instructions and got the following error: python setup.py install Error in %s at %d: %s ('setup.cfg', 21, "'[bdist_rpm]\\012'") Error in %s at %d: %s ('setup.cfg', 24, "'doc_files = CHANGES.txt\\012'") Traceback (innermost last): File "setup.py", line 13, in ? setup (name = "Distutils", File "distutils/core.py", line 110, in setup dist.parse_config_files() File "distutils/dist.py", line 323, in parse_config_files parser.read(filename) File "/usr/lib/python1.5/ConfigParser.py", line 154, in read self.__read(fp) File "/usr/lib/python1.5/ConfigParser.py", line 232, in __read cursect = cursect[optname] + '\n ' + value TypeError: expected integer index --------------------- end error message ---------------------- Sorry to bother you with this, but this is really what I know nothing about in Python. Any ideas as to how to do this thing? Cheers, Pijus ------------------------------------------------------------ PGP PUBLIC KEY: www.fas.harvard.edu/~virketis/links My weblog: www.fas.harvard.edu/~virketis From karthikg@aztec.soft.net Sun Oct 7 04:55:52 2001 From: karthikg@aztec.soft.net (karthik Guru) Date: Sun, 7 Oct 2001 09:25:52 +0530 Subject: [Tutor] [Q] list and loop In-Reply-To: <019a01c176f4$14ccabe0$95757e82@visit2> Message-ID: try this, map(None,list1,list2) karthik -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of Young-Jin Lee Sent: Tuesday, November 27, 2001 9:02 AM To: tutor@python.org Subject: [Tutor] [Q] list and loop Hi, I'd like to how to effectively create a list out of two lists. I have two lists, list1 = [ 1, 2, 3, 4, 5, .... 10] and list = [ 10, 20, 30, 40, .., 100]. I want to create another list out of these two lists such that list3 = [ (1,10), (2,20), (3,30), ..., (10, 100)]. I think there must be an elegant way in python using for loop, but I couldn't figure it out. Thanks in advance. YJ _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From schoeller@zkm.de Thu Oct 4 14:05:46 2001 From: schoeller@zkm.de (=?ISO-8859-1?Q?Andreas_Sch=F6ller?=) Date: Thu, 4 Oct 2001 15:05:46 +0200 Subject: [Tutor] [Q] xmlrpcsvr session & threads Message-ID: <86A66E6C-B8C8-11D5-8ED3-0003937266F6@zkm.de> Hello Tutor(s), i=B4m using Fredrik Lundh=B4s xmlrpcserver.py to supply data from a=20 mySQL-db. For performance reasons my app caches most of the compound=20 info read from the db in a couple of linked objects. This all works. Now=20= i want to track user requests and organize them in sessions. AFAIK this=20= can be done using cookies ? For browsers with cookies enabled, my=20 serving app needs to insert the cookie info into the http-header and=20 from that time on the browser will supply it on every following=20 request. I that correct ? I know the cookie module that will do that for=20= me. I can extract the complete header at the RequestHandler=B4s=20 call-method ,before any function starts : def call(self, meth_name, arg_tuple): self.location,self.no_clue =3D self.client_address self.header =3D self.headers ... BTW what represents the second value self.no_clue ? It=B4s a changing=20 integer-number ? Ok, now I can identify the user by it=B4s ip-addr and/or cookie - but = how=20 and where can i insert the cookie ? There=B4s a post-method where this=20= should be done, but i=B4m not sure where or how ? def do_POST(self): =09 try: # get arguments data =3D = self.rfile.read(int(self.headers["content-length"])) params, method =3D xmlrpclib.loads(data) # generate response try: response =3D self.call(method, params) if type(response) !=3D type(()): response =3D (response,) # wrap response in a singleton tuple #response =3D (response,) =09 except xmlrpclib.Fault, faultobj: # generated response was a Fault response =3D xmlrpclib.dumps(faultobj) print "xmlrpclib-Fault",response =09 except: # report exception back to server #print "Standard error..." response =3D = xmlrpclib.dumps(xmlrpclib.Fault(1,=20 "%s:%s" % (sys.exc_type, sys.exc_value))) else: response =3D = xmlrpclib.dumps(response,methodresponse=3D1) except: # internal error, report as HTTP server error print "Interner Fehler ! response=3D500" self.send_response(500) self.end_headers() else: # got a valid XML RPC response self.send_response(200) self.send_header("Content-type", "text/xml") self.send_header("Content-length", = str(len(response))) self.end_headers() self.wfile.write(response) # shut down the connection (from Skip Montanaro) self.wfile.flush() self.connection.shutdown(1) Maybe somebody can point me the right place where to modify the above=20 code-piece. Furthermore I thought about using threads to increase performance and=20 organize the sessions. The resulting amount of data gathered from the db=20= is low but number of involved tables is high - about 5-8 tables per=20 request. Does it make sense to create a thread per session, that will=20 care for the sessions-timeout , logging etc ? I have a feeling that by using threads i need to change my approach=20 considerably ? Can anybody advise me a direction like threads yes/no=20 because ..... the following problems will be small/huge... etc ,, the=20 performance gained will be reasonable/quite poor .. etc. ? thanks in advance ,,, andreas